Skip to content

Instantly share code, notes, and snippets.

@andresr-dev
Last active April 15, 2023 21:32
Show Gist options
  • Save andresr-dev/8a4aef4a8c5d77379d5da87cb6e9c149 to your computer and use it in GitHub Desktop.
Save andresr-dev/8a4aef4a8c5d77379d5da87cb6e9c149 to your computer and use it in GitHub Desktop.
This is how to detect screen recording and snapshot events in iOS using SwiftUI
import SwiftUI
@main
struct ScreenCaptureBlockerApp: App {
@State private var hidingScreen = false
private var window: UIWindow? {
guard
let scene = UIApplication.shared.connectedScenes.first,
let sceneDelegate = scene.delegate as? UIWindowSceneDelegate,
let uiWindow = sceneDelegate.window
else {
return nil
}
return uiWindow
}
var body: some Scene {
WindowGroup {
ZStack {
ContentView()
if hidingScreen {
Rectangle().ignoresSafeArea()
}
}
// Sends a notification when the contents of the screen are being recorded, mirrored,
// sent over AirPlay, or otherwise cloned to another destination.
.onReceive(NotificationCenter.default.publisher(for: UIScreen.capturedDidChangeNotification)) { _ in
hidingScreen = window?.screen.isCaptured ?? false
}
// Sends a notification after a screenshot is taken.
.onReceive(NotificationCenter.default.publisher(for: UIApplication.userDidTakeScreenshotNotification)) { _ in
print("User just took a screen shot")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment