Search code examples
swift2ios9swift3ios10xcode8

Detect screen lock or home button press on iOS9 and iOS10 in Swift 3


The answer provided by Rean Wen in this post worked great in Swift 2.2, but now I upgraded to XCode 8.0 with Swift 3 and it does not work anymore.

I am getting the following error message:

.../project/AppDelegate.swift:41:108: Cannot convert value of type '(@convention(c) (CFNotificationCenter?, UnsafeMutableRawPointer?, CFString?, UnsafeRawPointer?, CFDictionary?) -> Void)!' to expected argument type 'CFNotificationCallback!'

from this line:

CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), nil, LockNotifierCallback.notifierProc(), "com.apple.springboard.lockcomplete", nil, CFNotificationSuspensionBehavior.DeliverImmediately)

inside the AppDelegate.swift file.

Does anyone know how to solve this issue? Since I just started learning Swift, any help will be greatly appreciated.


Solution

  • This may work for you.

    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
                                        nil,
                                        { (_, observer, name, _, _) in
    
                                            print("received notification: \(name)")
            },
                                        "com.apple.springboard.lockcomplete" as CFString!,
                                        nil,
                                        .deliverImmediately)
    

    You can check this answer for more detail.