iOS推送API演变过程

2019-10-23  本文已影响0人  流年划过颜夕

iOS分为本地推送和远程推送。

首先是注册推送,演变过程如下:

//支持iOS8以下
   [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];

//支持iOS8以上
   [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge categories:nil]];

//支持iOS10以上(但需要引入框架UserNotifications)
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {}

接收:
最早分推送接收是单独分开接收的
本地推送:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{}

和远程推送:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{

  completionHandler(UIBackgroundFetchResultNewData);
}

但iOS10以后所有通知可以通过UNUserNotificationCenter来管理,包括远程通知和本地通知,而且方法调用机制也有变化,把以前一个接受远程推送和本地推送的接口合并为了一个,但是在统一成一个的前提下,又把调用过程拆分为了两种类型,通过代理来管理:

第一种为当app处于前台时,自动调用:

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    //应用在前台收到通知
    NSLog(@"========%@", notification);
    //如果需要在应用在前台也展示通知
completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
}

第二种为当app没有处于前台时,点击触发进入app,会调用:

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    //点击通知进入应用
    NSLog(@"response:%@", response);
}
上一篇 下一篇

猜你喜欢

热点阅读