iOS10推送之基础知识(必看篇)

2020-01-18 16:00:19于丽

第二步我们需要在 (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions中注册通知,代码如下:


 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

 if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
  //iOS10特有
  UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  // 必须写代理,不然无法监听通知的接收与点击
  center.delegate = self;
  [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
   if (granted) {
    // 点击允许
    NSLog(@"注册成功");
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
     NSLog(@"%@", settings);
    }];
   } else {
    // 点击不允许
    NSLog(@"注册失败");
   }
  }];
 }else if ([[UIDevice currentDevice].systemVersion floatValue] >8.0){
  //iOS8 - iOS10
  [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge categories:nil]];

 }else if ([[UIDevice currentDevice].systemVersion floatValue] < 8.0) {
  //iOS8系统以下
  [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
 }
 // 注册获得device Token
 [[UIApplication sharedApplication] registerForRemoteNotifications];

其中,获得Device Token的方法是没有改变的。


// 获得Device Token
 - (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
 NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
}
// 获得Device Token失败
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
 NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

此次iOS10系统的更新,苹果给了我们2个代理方法来处理通知的接收和点击事件,这两个方法在<UNUserNotificationCenterDelegate>的协议中,大家可以查看下。此外,苹果把本地通知跟远程通知合二为一。区分本地通知跟远程通知的类是UNPushNotificationTrigger.h类中,UNPushNotificationTrigger的类型是新增加的,通过它,我们可以得到一些通知的触发条件,在使用时,我们不应该直接使用这个类,应当使用它的子类。

我简单点说

1.UNPushNotificationTrigger (远程通知) 远程推送的通知类型

2.UNTimeIntervalNotificationTrigger