iOS的10及更高版本:
1)userNotificationCenter willPresent通知:一般用來決定何時用戶已經在應用程序中,並通知到達該怎麼辦。您可能會在應用程序內觸發遠程通知。在他點擊遠程通知後,方法2(didReceive響應)被調用。
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
//Handle push from foreground
//When a notification arrives and your user is using the app, you can maybe notify user by showing a remote notification by doing this
completionHandler([.alert, .badge, .sound])
//To print notification payload:
print(notification.request.content.userInfo)
}
2)userNotificationCenter didReceive響應:一般用於將用戶重定向到用戶敲擊該通知後該應用的特定屏幕。
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Void) {
//Handle push from background or closed (or even in foreground)
//This method is called when user taps on a notification
//To print notification payload:
print(response.notification.request.content.userInfo)
}
下面的iOS 10:
3)應用didReceiveRemoteNotification:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
//To print notification payload
print(userInfo)
if #available(iOS 10.0, *) {
}
else {
//Handle remote notifications for devices below iOS 10
if application.applicationState == .active {
//app is currently in foreground
}
else if application.applicationState == .background {
//app is in background
}
else if application.applicationState == .inactive {
//app is transitioning from background to foreground (user taps notification)
}
}
}
4)應用didFinishLaunchingWithOptions launchOptions:其被放置裝置之下的iOS 10的唯一情形當應用程序關閉時,用戶點擊啓動應用程序的通知。您必須檢查以下方法。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//To print notification payload:
if let notification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] {
print(notification)
}
}
LaunchOptions是指示該應用是 推出的原因(如果有的話)的字典。在用戶直接啓動應用程序的情況下,此字典的內容可能爲空,如 。
現在回答你的問題,
1)處理遠程通知時應用程序在後臺/無效,你必須添加代碼方法2(userNotificationCenter didReceive響應)與設備iOS 10及以上版本。另外,對於iOS 10以下的設備,您必須使用方法3(應用程序didReceiveRemoteNotification)。
2)要在iOS 10之前的應用程序在前臺運行時處理遠程通知,請使用方法3活動狀態。