远程推送是指服务端给客户端发送消息时,客户端能接收并且如果程序处于后台状态时还能弹出推送窗口,即使程序不在后台运行时也能进行推送,像微信、QQ那样。
要实现远程推送,需要以下步骤:
1.在工程项目的capabilites将Push Notifications打开,此时会在项目中生成一个entitlements文件
屏幕快照 2017-12-11 20.45.15.png
2.在appdelegate中申请推送权限
//iOS10及以上系统申请方式
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
//必须写代理,不然无法监听通知的接收与点击事件
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error && granted) {
NSLog(@"用户点击允许,注册成功");
}else {
NSLog(@"用户点击不允许,注册失败");
}
}];
//iOS8到iOS10系统申请方式
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
[application registerUserNotificationSettings:settings];
3.在appdelegate中添加代码,以获取device token
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSString *deviceString = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
deviceString = [deviceString stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"deviceToken===========%@",deviceString);
}
//在这里接收远程推送的信息
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
NSLog(@"iOS7及以上系统,收到通知:%@", userInfo);
completionHandler(UIBackgroundFetchResultNewData);
}
4..申请一个push证书
屏幕快照 2017-12-11 20.50.16.png
5.准备完毕,开始模拟远程推送,下载第三方工具pusher,在钥匙串中将push证书导出p12文件,在pusher工具中导入,并且添加刚刚获取的device token,文本框内为push内容,可以直接使用进行测试,点击push,即可在手机端看到实现效果,注意,需要在真机上进行测试。
屏幕快照 2017-12-11 20.55.07.png
网友评论