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 response:一般用于在用户点击通知后将用户重定向到应用的特定屏幕。
@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 是一个字典,指示应用程序的原因
启动(如果有)。这个字典的内容可能是空的
用户直接启动应用的情况。
现在回答你的问题,
-
要在应用处于后台/非活动状态时处理远程通知,您必须在方法 2(userNotificationCenter didReceive 响应)中为 iOS 10 及更高版本的设备添加代码。此外,对于 iOS 10 以下的设备,您必须使用方法 3(应用程序 didReceiveRemoteNotification)。
-
要在iOS 10之前应用在前台运行时处理远程通知,请使用方法3活动状态。