从iOS 10中的本地通知启动应用程序

时间:2017-04-20 09:59:23

标签: ios swift unnotificationrequest

我正在尝试使用iOS 10中本地通知的操作实现应用启动(从非活动状态)。

我已关注Launch a local notification at a specific time in iOS,应用程序启动正常以响应本地通知。但我想从这里得到的是响应通知中的数据执行操作。

在iOS 8和9中,我在AppDelegate中进行了设置

func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
    if (application.applicationState == UIApplicationState.inactive || application.applicationState == UIApplicationState.background) {
        NotificationCenter.default.post(name: Notification.Name(rawValue: "noteName", object: notification.alertBody)

并且观察者在ViewController中捕获它

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.txtFromNotifier), name: NSNotification.Name(rawValue: "noteName", object: nil)

现在在iOS 10中的AppDelegate:

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    // Determine the user action
    switch response.actionIdentifier {
    case UNNotificationDismissActionIdentifier:
        print("Dismiss Action")
    case UNNotificationDefaultActionIdentifier:
        print("Default")
        // do something here

我还没有能够找到如何从UNNotification Default操作("默认"在启动后在控制台中打印)到传递参数并在ViewController中执行txtFromNotifier函数。尝试使用NotificationCenter post / addObserver组合在应用程序处于后台但在应用程序处于非活动状态时无法到达时可以正常工作。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我对通知广播进行了延迟。我的AppDelegate现在看起来像这样。用于在didFinishLaunchingWithOptions中选择通知中心:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    if #available(iOS 10.0, *) {
        let center = UNUserNotificationCenter.current()
        center.delegate = self
        let options: UNAuthorizationOptions = [.alert, .badge, .sound]
        center.requestAuthorization(options: options) {
            (granted, error) in
            if !granted {
                print("Something went wrong")
            }
        }
    } else {
        application.registerUserNotificationSettings(UIUserNotificationSettings(types: [.alert , .badge , .sound], categories: nil))
    }
    return true
}

在didReceiveNotification中,我选择了iOS 10 ...

func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
    if #available(iOS 10.0, *) {
        // different notification centre for iOS 10, see @available below
    } else {
        if (application.applicationState == UIApplicationState.inactive || application.applicationState == UIApplicationState.background) {
            runAfterDelay(2.0) {  // 2 second delay, not sure if needed but doesn't seem to hurt - runAfterDelay function is below
                NotificationCenter.default.post(name: Notification.Name(rawValue: NSLocalizedString("ticker_notification_name", comment: "")), object: notification.alertBody)
            }
        } /*else {
         // handle the local notification when the app is open, if needed
         } */
    }
}

并使用@available选项为iOS 10选择:

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    // Determine the user action
    switch response.actionIdentifier {
    case UNNotificationDismissActionIdentifier:
        print("Dismiss Action")
    case UNNotificationDefaultActionIdentifier:
        print("Default")
        runAfterDelay(3.0) {  // 3 second delay to give observer time to load. 3 seconds is arbitrary. runAfterDelay function is below
            NotificationCenter.default.post(name: Notification.Name(rawValue: NSLocalizedString("ticker_notification_name", comment: "")), object: response)  // .body
        }
    case "Snooze":
        print("Snooze")
    case "Delete":
        print("Delete")
    default:
        print("Unknown action")
    }
    completionHandler()
}

以及runAfterDelay函数,它使观察者有时间放置袜子:

func runAfterDelay(_ delay: Double, closure:@escaping ()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}

我认为我不需要对观察者进行任何更改 - 我没有看到修订历史记录中的任何更改,它看起来与原始问题中的addObserver方法相同。