如何检测用户是否已采取操作本地通知或远程通知?

Tec*_*ain 4 notifications ios swift unusernotificationcenter

我在我的应用中显示本地和远程通知.现在有一种情况,如果通知是本地的,那么我想采取不同的行动,或者如果通知是远程的,那么我想采取一些不同的行动.

直到iOS 9我使用下面的代码来检测通知是本地还是远程.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {


    if launchOptions?[UIApplicationLaunchOptionsKey.localNotification] != nil {
        // Do what you want to happen when a remote notification is tapped.
    }
    return true
  }
Run Code Online (Sandbox Code Playgroud)

但是在iOS 10中这种方法已被弃用,所以现在如何确保通知是本地的还是远程的?

nRe*_*wik 11

适用于iOS 10及以上版本的UserNotifications框架.

检查用户是否对通知采取了操作.您可以遵守UNUserNotificationCenterDelegate并实施userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:

检查它是否是远程通知.您可以检查类型trigger,因为远程通知触发器是UNPushNotificationTrigger.

这是代码......

#pragma mark - UNUserNotificationCenterDelegate

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler {

    if ([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        // User did tap at remote notification
    }

    completionHandler();
}
Run Code Online (Sandbox Code Playgroud)


iVa*_*run 5

UNMutableNotificationContent附加userInfo在象下面这样:

content.userInfo = ["isLocalNotification" : true]
Run Code Online (Sandbox Code Playgroud)

现在,在AppDelegate一套UNUserNotificationCenterDelegatedidFinishLaunchingWithOptions象下面这样:

UNUserNotificationCenter.current().delegate = self
Run Code Online (Sandbox Code Playgroud)

然后实现didReceive response方法UNUserNotificationCenterDelegate

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

        print(response.notification.request.content.userInfo)
    }
Run Code Online (Sandbox Code Playgroud)

在输出中,您将得到如下内容:

[AnyHashable("isLocalNotification"): 1]

您可以使用isLocalNotification密钥识别本地通知。