iOS本地推送(附Swift与OC代码)

一、前言

上一篇文章讲述了下关于远程推送用到的两种类型APNS与VoIP。本篇就来教你实现本地推送。

二、iOS本地推送的前世今生

iOS本地推送现阶段以iOS10系统为界线出现了一次跃进。iOS10+的本地推送与iOS10之前的本地推送在现象上一个很大的不同就是

iOS10以前的本地推送,当App运行在前台的时候。系统alert是弹不出来的

三、实现步骤

  • 在didFinishLaunchingWithOptions方法里注册推送
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0)
{
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error) {
                NSLog(@"推送注册成功");
            }
        }];
        [application registerForRemoteNotifications];
} else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0 && [[UIDevice currentDevice].systemVersion floatValue] < 10) {//iOS8-iOS10
        
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound) categories:nil];
        [application registerUserNotificationSettings:settings];
        [application registerForRemoteNotifications];
} else { //iOS8以下
        
        // [application registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
}

这里插一句,远程推送区分是否是点击推送启动的App,可以在上面方法里做以下处理

NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
userInfo就是推送的信息数据,如果userInfo不为空,则可以说明是点击推送启动的App。
  • 处理iOS10+的推送代理方法
    此处有两个代理方法。一个是即将弹出推送通知的代理,一个是点击推送通知栏的代理
#pragma mark - iOS10-UNUserNotificationCenterDelegate
// 弹出通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}

// 点击通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
    // 可以在这里做跳转处理
    completionHandler();
}
  • 处理iOS10以下的推送相关方法
// iOS10以下,注册推送
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    
    //register to receive notifications
    [application registerForRemoteNotifications];
}

// iOS10以下,点击走这个方法
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    // 可以在这里做跳转处理
    NSLog(@"%@", notification.userInfo);
}
  • 模拟发起推送
    注:iOS10以下的需要在推送5秒钟之内推到后台,方能有效果
// 10系统以上
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0)
{
        // 1.设置触发条件
        UNTimeIntervalNotificationTrigger *timeTrigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:.5f repeats:NO];
        // 2.创建通知内容
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        content.body = @"我是小明";
        content.badge = @([UIApplication sharedApplication].applicationIconBadgeNumber + 1);
        content.sound = [UNNotificationSound defaultSound];
        NSString *detail = @"其实他是假小明";
        content.userInfo = @{
                             @"detail":detail
                             };
        // 3.通知标识
        NSString *requestIdentifier = [NSString stringWithFormat:@"%lf", [[NSDate date] timeIntervalSince1970]];
        // 4.创建通知请求,将1,2,3添加到请求中
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier content:content trigger:timeTrigger];
        // 5.将通知请求添加到通知中心
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
           
            if (!error)
            {
                NSLog(@"推送已经添加成功");
            }
        }];
} else { // iOS10以下
        
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.alertBody = @"我是小明";
        notification.applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber + 1;
        notification.soundName = UILocalNotificationDefaultSoundName;
        NSString *detail = @"其实他是假小明";
        notification.userInfo = @{
                                  @"detail":detail
                                  };
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            // 执行此代码之前进入后台
            [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
        });
}

最后附上demo地址:
iOS本地推送_OC版
iOS本地推送_Swift版

你可能感兴趣的:(iOS本地推送(附Swift与OC代码))