Skip to content

Instantly share code, notes, and snippets.

@pauljohanneskraft
Last active December 13, 2018 15:31
Show Gist options
  • Save pauljohanneskraft/1cfc92e30712279eefc0d43e746c51a3 to your computer and use it in GitHub Desktop.
Save pauljohanneskraft/1cfc92e30712279eefc0d43e746c51a3 to your computer and use it in GitHub Desktop.
ScreenMonitoringNotifier

ScreenMonitoringNotifier

ScreenMonitoringNotifier uses a timer with a specific timeInterval - default is 1 second - to check whether any screen is potentially being monitored. Potentially being monitored includes active screen recordings and the use of external displays.

Use ScreenMonitoringNotifier.shared to send out notifications or instantiate your own ScreenMonitoringNotifier to use callbacks.

@available(iOS 10.0, *)
public class ScreenMonitoringNotifier {
// MARK: - Static properties
public static let isRecordingNotification = Notification.Name(String(describing: ScreenMonitoringNotifier.self) + "." + #function)
public static let isRecordingNotificationKey = "isRecording"
public static let shared = ScreenMonitoringNotifier { isRecording in
NotificationCenter.default.post(name: isRecordingNotification, object: nil, userInfo: [isRecordingNotificationKey: isRecording])
}
// MARK: - Stored properties
private let callback: (Bool) -> Void
private var timer: Timer?
public private(set) var lastStatus: Bool?
// MARK: - Init
public init(timeInterval: TimeInterval = 1, callback: @escaping (Bool) -> Void) {
self.callback = callback
restartTimer(withInterval: timeInterval)
lastStatus = isRecordingOrMirroring()
}
// MARK: - Methods
public func restartTimer(withInterval interval: TimeInterval? = nil) {
let interval = interval ?? timer?.timeInterval ?? 1
self.timer?.invalidate()
self.timer = Timer(timeInterval: interval, repeats: true, block: { [weak self] _ in self?.timerExpired() })
}
// MARK: - Helpers
private func timerExpired() {
let currentStatus = isRecordingOrMirroring()
defer { lastStatus = currentStatus }
if currentStatus != lastStatus { callback(currentStatus) }
}
private func isRecordingOrMirroring() -> Bool {
for screen in UIScreen.screens {
if #available(iOS 11.0, *) {
guard !screen.isCaptured else { return true }
}
guard screen.mirrored == nil else { return true }
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment