SwiftUI如何检测用户截屏或录屏

6

UIViewController 中,我们可以轻松地向控制器添加观察者。例如:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(didTakeScreenshot(notification:)), name: UIApplication.userDidTakeScreenshotNotification, object: nil)
    }
    
    @objc func didTakeScreenshot(notification: Notification) {
        print("Screen Shot Taken")
    }
}

使用以下方法进行记录:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    let isCaptured = UIScreen.main.isCaptured
    return true
}

但是如何在SwiftUI中实现呢?

1个回答

10

这里是一个简单的演示:

struct ContentView: View {
    @State var isRecordingScreen = false
    
    var body: some View {
        Text("Test")
            .onReceive(NotificationCenter.default.publisher(for: UIApplication.userDidTakeScreenshotNotification)) { _ in
                print("Screenshot taken")
            }
            .onReceive(NotificationCenter.default.publisher(for: UIScreen.capturedDidChangeNotification)) { _ in
                isRecordingScreen.toggle()
                print(isRecordingScreen ? "Started recording screen" : "Stopped recording screen")
            }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接