当应用程序处于后台时,UserNotificationCenterDelegate的替代品将会显示

时间:2017-06-08 02:36:06

标签: ios apple-push-notifications uilocalnotification unusernotificationcenter usernotifications

我想弄清楚我是否可以通过本地通知完成目标,或者是否需要切换到远程通知。

我通过制作一个闹钟程序来练习iOS 10 / Swift 3,该闹钟程序在一天中的某个时间播放RSS更新的电台节目的最新一集。当应用程序位于前台时,可以通过UNUserNotificationCenterDelegate的willPresent函数轻松执行。我只是使用willPresent来获取最新的剧集,并通过AVAudio播放器播放。

当然,如果应用程序仅在前台工作,则此功能非常有限。我希望应用程序在后台或关闭时以相同的方式工作。

我可以从文档中看到,当应用程序不在前台时,willPresent不会运行。当应用程序在后台时,是否有其他方法让本地通知在推送通知之前执行代码?或者我是否必须切换到远程通知?我看到this answer to a related question,但我想知道是否有更优雅的方法。

1 个答案:

答案 0 :(得分:2)

对于 iOS 10 本地通知您的运气不好。

对于 iOS 10 远程通知 - ,无论用户互动,您都可以使用application(_:didReceiveRemoteNotification:fetchCompletionHandler:)接收回调。 (他们弃用了大多数与通知相关的方法而不是这个方法,这有点令人困惑)

当应用处于前台并且即将显示通知时回调:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let content = notification.request.content
    // Process notification content

    completionHandler([.alert, .sound]) // Display notification as regular alert and play sound
}

当app处于后台或前台且用户点击操作时回调:

enter image description here

e.g。为您提供用户点击保存的回调。

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    let actionIdentifier = response.actionIdentifier

    switch actionIdentifier {
    case UNNotificationDismissActionIdentifier: // Notification was dismissed by user
        // Do something
        completionHandler()
    case UNNotificationDefaultActionIdentifier: // App was opened from notification
        // Do something
        completionHandler()
    default:
        completionHandler()
    }
}

当app处于后台,前台或(可能)暂停状态且推送通知(远程或无声通知)到达时回调:

在iOS10之前,当您点击通知时,application(_:didReceiveRemoteNotification:fetchCompletionHandler:)会被调用。

但是,因为点击未调用iOS 10 application(_:didReceiveRemoteNotification:fetchCompletionHandler:)。它仅在远程通知的到达上调用。 (它在前景和后台都被称为)

对于 pre iOS 10 ,您只需使用旧的didReceiveLocalNotification功能并捕获任何通知的到来。