在 iOS 中检查设备屏幕打开或关闭

Check Device screen On or Off in iOS

你好,我正在使用下面的代码来检查设备的屏幕是打开还是关闭。我从 this SO post.

得到了这段代码

代码:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), nil, displayStatusChanged, "com.apple.springboard.lockcomplete", nil, CFNotificationSuspensionBehavior.deliverImmediately)
        //CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), nil, displayStatusChanged, "com.apple.springboard.lockstate", nil, CFNotificationSuspensionBehavior.deliverImmediately)

        return true
    }
}//AppDelegate class end here

func displayStatusChanged(center:CFNotificationCenter,observer: UnsafeMutableRawPointer?,name:CFString,object: UnsafeRawPointer?,userInfo:CFDictionary) -> Void {

}

但是我得到了这个错误:

Cannot convert value of type '(CFNotificationCenter, UnsafeMutableRawPointer?, CFString, UnsafeRawPointer?, CFDictionary) -> Void' to expected argument type 'CFNotificationCallback!' (aka 'ImplicitlyUnwrappedOptional<@convention(c) (Optional, Optional, Optional, Optional, Optional) -> ()>')

有谁知道我在 displayStatusChanged 函数上做错了什么?任何帮助、建议或 link 将不胜感激。

谢谢

根据the documentation

  • center 参数应该是可选的(即缺少 ?),
  • 对于 name 你有 CFString 但文档说 CFNotificationName?
  • 并且 CFDictionary 应该是可选的(您缺少 ?),

如果您将参数与预期类型相匹配,应该可以修复您的错误。

func displayStatusChanged(center: CFNotificationCenter?, observer: UnsafeMutableRawPointer?, name: CFNotificationName?, object: UnsafeRawPointer?, userInfo: CFDictionary?) -> Void {

}