Reputation: 5410
On UIViewController
we can easy add observer to controller. Like:
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")
}
}
Or capturing record with:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let isCaptured = UIScreen.main.isCaptured
return true
}
But how to do it with SwiftUI?
Upvotes: 8
Views: 3936
Reputation: 1581
Nowadays you probably want EnvironmentValues.isSceneCaptured
iOS 17 and forward
Upvotes: 2
Reputation: 54576
Here is a simple demo:
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")
}
}
}
Upvotes: 12