SecureScreen.ios.kt
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.ios.kt
1@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)23package eu.friedcutlet.yokan.ui45import androidx.compose.runtime.Composable6import androidx.compose.runtime.DisposableEffect7import platform.Foundation.NSNotificationCenter8import platform.Foundation.NSOperationQueue9import platform.UIKit.UIApplication10import platform.UIKit.UIApplicationDidBecomeActiveNotification11import platform.UIKit.UIApplicationWillResignActiveNotification12import platform.UIKit.UIColor13import platform.UIKit.UIScreen14import platform.UIKit.UIScreenCapturedDidChangeNotification15import platform.UIKit.UIView16import platform.UIKit.UIViewAutoresizingFlexibleHeight17import platform.UIKit.UIViewAutoresizingFlexibleWidth18import platform.UIKit.UIWindow19import platform.UIKit.UIWindowScene2021@Composable22internal actual fun SecureScreenEffect(secure: Boolean) {23 DisposableEffect(secure) {24 IosPrivacyShield.enabled = secure25 onDispose { }26 }27}2829/**30 * iOS cannot block screenshots with public API. While enabled, a cover hides the UI in the app31 * switcher snapshot (taken after resign-active) and while the screen is recorded or mirrored.32 */33private object IosPrivacyShield {34 private var cover: UIView? = null35 private var inactive = false36 private var observing = false3738 var enabled = false39 set(value) {40 field = value41 if (value) observe()42 refresh()43 }4445 private fun observe() {46 if (observing) return47 observing = true48 val center = NSNotificationCenter.defaultCenter49 val queue = NSOperationQueue.mainQueue50 center.addObserverForName(UIApplicationWillResignActiveNotification, null, queue) { _ -> inactive = true; refresh() }51 center.addObserverForName(UIApplicationDidBecomeActiveNotification, null, queue) { _ -> inactive = false; refresh() }52 center.addObserverForName(UIScreenCapturedDidChangeNotification, null, queue) { _ -> refresh() }53 }5455 private fun refresh() {56 val hide = enabled && (inactive || UIScreen.mainScreen.isCaptured())57 if (!hide) {58 cover?.removeFromSuperview()59 cover = null60 return61 }62 if (cover != null) return63 val window = UIApplication.sharedApplication.connectedScenes64 .filterIsInstance<UIWindowScene>()65 .flatMap { it.windows }66 .filterIsInstance<UIWindow>()67 .let { windows -> windows.firstOrNull { it.isKeyWindow() } ?: windows.firstOrNull() }68 ?: return69 cover = UIView(frame = window.bounds).apply {70 backgroundColor = UIColor.blackColor71 autoresizingMask = UIViewAutoresizingFlexibleWidth or UIViewAutoresizingFlexibleHeight72 window.addSubview(this)73 }74 }75}76