iOS_RemotePush_远程推送

RemotePush的工作原理

远程推送原理

远程推送原理图

RemotePush的环境搭建

  • 登录Developer,添加AppID、创建对应的Development(测试)证书
    • 如何生成对应的CSR文件
      1. 打开钥匙串、选择左上角的钥匙串访问->证书助理->从证书颁发机构请求证书
        这里写图片描述
      2. 填写对应的信息
        这里写图片描述
      3. 在桌面将会生成一个CertificateSigningRequest.certSigningRequest 文件,即我们所需要的CSR文件
  • 下载并安装.cer证书,点击安装成功后,会弹出钥匙串到登录/证书界面。
  • 选择证书、然后右键导出证书。一个后缀为.p12 的文件、证书密码可以设置也可以不设置。
  • 在工程AppDelegate.m内对应位置添加调用代码
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [self registerAPN];
    return YES;
}
- (void)registerAPN {
    // 在此根据版本不同,设置不同的注册方式
    UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
}
// 用户允许通知,会进入此回调
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
    // 注册通知
    [application registerForRemoteNotifications];
}
// 注册成功的回调
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    // 在此回调中获得deviceToken
    NSString *tokenString = [NSString stringWithFormat:@"%@",deviceToken];
    // 对数据进行处理,删除<、>、空格
    tokenString = [tokenString stringByReplacingOccurrencesOfString:@" " withString:@""];
    tokenString = [tokenString stringByReplacingOccurrencesOfString:@"<" withString:@""];
    tokenString = [tokenString stringByReplacingOccurrencesOfString:@">" withString:@""];
    // 将处理好的tokenString上传给服务器
}
// 注册失败的回调
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{

}
  • 在苹果开发者网站、下图位置创建证书
    下载生成的证书.mobileprovision文件 并安装此证书
    这里写图片描述
  • 安装证书之后,在工程中图示位置、选择此证书
    这里写图片描述
    个人测试、可以应用一个GitHub的一个开源项目(nwpusher),向我们的测试机进行消息的推送。
    可以在github上搜索项目名称获取,也可以从下述网址,我的个人代码库获取。
    可以点击图示位置、到下级页面进行pusher的下载。
    这里写图片描述
    开源项目地址https://github.com/FlyingKuiKui/NWPusher
  • 根据对应的设置进行设置。然后就可以点击push,发送消息。
    这里写图片描述
    “alert”: 推送的消息内容
    “badge”:icon上小红点的显示的数字
    “sound”:推送时的声音
  • 手机就可以收到推送的消息

Push的交互设置

获取Push权限

  • 处理iOS不同版本下push设置的不同,以iOS8为分界线
- (void)registerAPN {
    // 在此根据版本不同,设置不同的注册方式 以ios8为分界线
    if([UIDevice currentDevice].systemVersion.floatValue >= 8.0){
        UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
    }else{
        // ios7以下
        // 由于目前Xcode8.3.3新创建工程最低版本支持8.0,因此新的项目中可以不添加此段代码
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert ];
    }
}

提示用户开启Push

  • 由于各类app业务的不同,可能用户在关闭推送之后,我们需要在用户多次让app进入后台之后提示用户开启推送功能。
  • 这个时候,我们可以用沙盒内的Library文件夹下的Preferences文件来记录用户进入app后台的次数。
// AppDelegate.m内方法 程序进入后台时触发
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    NSInteger times = [[[NSUserDefaults standardUserDefaults] objectForKey:@"GoBackground"] integerValue];
    times++;
    [[NSUserDefaults standardUserDefaults]setInteger:times forKey:@"GoBackground"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
  • 在用户唤起app的时候,我们可以提示用户开启推送权限
// AppDelegate.m内方法 程序唤起时触发
- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    NSInteger times = [[[NSUserDefaults standardUserDefaults] objectForKey:@"GoBackground"] integerValue];
    if (times >= 3) {
        // ios9之后 将会被UIAlertController替代
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"打开推送权限" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"允许", nil];
        [alert show];
    }

}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex != 0) {
        // 用户点击允许 ios8之后,可以直接调转手机设置界面
        if([UIDevice currentDevice].systemVersion.integerValue >= 8.0){
            [self goToSetting];
        }
    }
}
// 跳转到设置界面
- (void)goToSetting{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
  • 远程推送的回调
#pragma mark - RemotePush
// 远程推送 回调 在iOS10之后将会 分成三个方法回调
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{

}

iOS10之后远程推送

推送配置

  • 导入<UserNotifications/UserNotifications.h>
  • 遵循协议UNUserNotificationCenterDelegate
  • 打开对应的开关,图示位置
    这里写图片描述
    这个时候会生成图示文件、后缀为.entitlements文件:
    这里写图片描述

注册推送

// 需要导入 <UserNotifications/UserNotifications.h>
        UNUserNotificationCenter *notifiCenter = [UNUserNotificationCenter currentNotificationCenter];
        notifiCenter.delegate = self;
        [notifiCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                // 注册成功
                [notifiCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                    NSLog(@"%@",settings);
                }];
            }else{
                // 注册失败
            }
        }];

推送回调

#pragma mark - UNUserNotificationCenterDelegate 
// iOS10 推送回调
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
    NSDictionary *userInfo = notification.request.content.userInfo;
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; //收到推送消息的全部内容
    NSNumber *badge = content.badge; // 推送消息的角标
    NSString *body = content.body; // 收到推送消息具体内容
    UNNotificationSound *sound = content.sound; //声音
    NSString *subTitle = content.subtitle; // 推送收到的副标题
    NSString *title = content.title; // 推送收到的标题

    if ([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"iOS10 收到远程通知");
    }else{
        NSLog(@"ios10 收到本地通知%@%@%@%@%@",title,subTitle,body,badge,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge |
                      UNNotificationPresentationOptionSound |
                      UNNotificationPresentationOptionAlert );
    // 需要执行此方法,选择是否提醒用户,有以上三种那个类型可选

}
// 通知的点击事件
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request;
    UNNotificationContent *content = request.content; //收到推送消息的全部内容
    NSNumber *badge = content.badge; // 推送消息的角标
    NSString *body = content.body; // 收到推送消息具体内容
    UNNotificationSound *sound = content.sound; //声音
    NSString *subTitle = content.subtitle; // 推送收到的副标题
    NSString *title = content.title; // 推送收到的标题
    NSLog(@">>>通知的点击事件");
    if ([request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"iOS10 收到远程通知");
    }else{
        NSLog(@"ios10 收到本地通知%@%@%@%@%@",title,subTitle,body,badge,userInfo);
    }
    completionHandler(); //系统要求执行此方法,必须写

}

代码地址:https://github.com/FlyingKuiKui/PushTestApp.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值