Flutter iOS端防止截屏

最近项目中需要实现防止截屏功能,网上很多都是推荐使用flutter_forbidshot,但是这个只能设置Android端,iOS端是用户截屏后发出通知,也就是说iOS端并不能禁止用户截屏。

当然iOS端也有禁止截屏的功能可以参考iOS截屏防护-担心App内容被截屏泄露吗?这个开源库就是你要的具体原理讲的很清楚。

  private func makeSecureView() -> UIView? {
        let tf = UITextField()
        tf.isSecureTextEntry = true
        let fv = tf.subviews.first
        fv?.subviews.forEach { $0.removeFromSuperview() }
        fv?.isUserInteractionEnabled = true
        return fv
    }

于是就使用自定义FlutterViewController方式并重写loadView()方法将view替换成makeSecureView(),但这时出现了一个问题:运行后项目中除了flutter自带Icons的所有图片都不显示了,如果你知道为什么会这样请评论区告诉俺,谢谢。

经过尝试,可以重写viewDidLoad()方法,将view替换成防截图的view,再将控制器的原view添加到新的view上,说起来有点麻烦,全部代码如下:

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
      window = UIWindow.init(frame: UIScreen.main.bounds)
      window.backgroundColor = .white
      let vc = FViewController()
      window.rootViewController = vc
      
      GeneratedPluginRegistrant.register(with: self)
      
      FlutterChannel.default.registMessageChannel(with: vc.binaryMessenger)
      
      return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}


/// 自定义根控制器 - 继承自FlutterViewController
class FViewController: FlutterViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let v = view // 取出原view
        v?.backgroundColor = .white // 背景色 - 截图的颜色
        v?.frame = .zero // 不能设置为UIScreen.main.bounds
        view = makeSecureView() // 生成防截图view
        view.addSubview(v!) // 必须将原view添加到当前view上
    }
    
    /// 生成防截图view
    private func makeSecureView() -> UIView? {
        let tf = UITextField()
        tf.isSecureTextEntry = true // 必须是true,否则无法禁止截图
        let fv = tf.subviews.first
        fv?.subviews.forEach { $0.removeFromSuperview() }
        fv?.isUserInteractionEnabled = true // 开启交互
        return fv
    }
}

注意:

1、自定义的控制器必须继承自FlutterViewController,否则在AppDelegate中会报错,因为这个AppDelegate其实是FlutterAppDelegate里面实现了flutter与原生交互的channel等功能
2、v?.frame = .zero,frame必须设置且不能为全屏,否则项目中的所有元素变大,导致显示不全,具体原理不清楚
3、必须将原view添加到新view上,否则项目页面不显示
4、可以将let tf = UITextField()设置为全局变量,并通过flutter与原生交互设置tf.isSecureTextEntry来开启和关闭防截屏功能

该方式是全局防止截屏,若要实现页面的某一部分防止截屏应该也类似,主要区别应该是将自定义FlutterViewController换成自定义UIView,俺没有试过

iOS防截屏功能就这些了,当然这个只是本人仓促间想到的方法,不一定是最好的,有问题请您指正,如果您有更好的方法也可以分享出来让大家共同学习,感谢。

Just Do IT!

你可能感兴趣的:(Flutter iOS端防止截屏)