2016-10-06 15 views
0

Ответ Rean Wen в этом post отлично справился с Swift 2.2, но теперь я обновился до XCode 8.0 с помощью Swift 3, и он больше не работает.Обнаружение блокировки экрана или нажатие кнопки дома на iOS9 и iOS10 в Swift 3

Я получаю следующее сообщение об ошибке:

.../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

Это может сработать для вас.

CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), 
            nil, 
            { (_, observer, name, _, _) in 

             print("received notification: \(name)") 
     }, 
            "com.apple.springboard.lockcomplete" as CFString!, 
            nil, 
            .deliverImmediately) 

Вы можете проверить это answer более подробно.

-1

У меня возникла та же проблема, когда я недавно разрабатывал приложение для управления задачами. Я пытаюсь решить эту проблему, используя уведомление Darwin с методом CFNotificationCallback.

Шаг 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