Rean Wen在此post中提供的答案在Swift 2.2中运行得很好,但现在我使用Swift 3升级到XCode 8.0,它不再起作用了。
我收到以下错误消息:
.../project/AppDelegate.swift:41:108: Cannot convert value of type '(@convention(c) (CFNotificationCenter?, UnsafeMutableRawPointer?, CFString?, UnsafeRawPointer?, CFDictionary?) -> Void)!' to expected argument type 'CFNotificationCallback!'
从这一行:
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), nil, LockNotifierCallback.notifierProc(), "com.apple.springboard.lockcomplete", nil, CFNotificationSuspensionBehavior.DeliverImmediately)
在AppDelegate.swift文件中。
有谁知道如何解决这个问题?自从我刚刚开始学习Swift以来,我们将非常感谢任何帮助。
答案 0 :(得分:0)
这可能适合你。
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
nil,
{ (_, observer, name, _, _) in
print("received notification: \(name)")
},
"com.apple.springboard.lockcomplete" as CFString!,
nil,
.deliverImmediately)
您可以查看answer以获取更多详细信息。
答案 1 :(得分:-1)
我最近在开发任务管理应用时遇到了同样的问题。我尝试使用带有CFNotificationCallback方法的Darwin Notification来解决这个问题。
步骤1:在AppDelegate类声明
下添加以下代码class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let displayStatusChanged: CFNotificationCallback = { center, observer, name, object, info in
let str = name!.rawValue as CFString
if (str == "com.apple.springboard.lockcomplete" as CFString) {
let isDisplayStatusLocked = UserDefaults.standard
isDisplayStatusLocked.set(true, forKey: "isDisplayStatusLocked")
isDisplayStatusLocked.synchronize()
}
}
//other functions
}
第2步:
在didFinishLaunchingWithOptions
内,添加以下代码:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let isDisplayStatusLocked = UserDefaults.standard
isDisplayStatusLocked.set(false, forKey: "isDisplayStatusLocked")
isDisplayStatusLocked.synchronize()
// Darwin Notification
let cfstr = "com.apple.springboard.lockcomplete" as CFString
let notificationCenter = CFNotificationCenterGetDarwinNotifyCenter()
let function = displayStatusChanged
CFNotificationCenterAddObserver(notificationCenter,
nil,
function,
cfstr,
nil,
.deliverImmediately)
return true
}
第3步:
在applicationDidEnterBackground
内,添加以下代码:
func applicationDidEnterBackground(_ application: UIApplication) {
let isDisplayStatusLocked = UserDefaults.standard
if let lock = isDisplayStatusLocked.value(forKey: "isDisplayStatusLocked"){
// user locked screen
if(lock as! Bool){
// do anything you want here
print("Lock button pressed.")
}
// user pressed home button
else{
// do anything you want here
print("Home button pressed.")
}
}
}
第4步:
在applicationWillEnterForeground
内,添加以下代码:
func applicationWillEnterForeground(_ application: UIApplication) {
print("Back to foreground.")
//restore lock screen setting
let isDisplayStatusLocked = UserDefaults.standard
isDisplayStatusLocked.set(false, forKey: "isDisplayStatusLocked")
isDisplayStatusLocked.synchronize()
}
您可以通过演示项目查看详细方法:swift-home-vs-lock-button