闲话少叙,直接上步骤:
1.获取LeanCloud应用信息: AppID和AppKey
2.获取用户的应用通知权限
3.获取deviceToken并提交给LeanCloud服务器.
4.订阅频道
5.创建AVPush对象发布消息到指定的频道
6.接受推送到的消息
7.退出频道
1. 获取LeanCloud应用信息
- 到LeanCloud官网注册开发者—>创建应用—> 获取应用的AppID和AppKey
本过程请认真参考LeanCloud官方文档进行操作.
2. 获取应用通知权限
- iOS 8以前的版本
1 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ... // Register for push notifications [application registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound]; ... } |
- iOS8以后的版本
1 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ... UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]; [application registerUserNotificationSettings:settings]; [application registerForRemoteNotifications]; ... } |
建议: 关于系统版本的选择,可以考虑使用条件编译.
3. 获取deviceToken并保存到服务器
1 | - (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { AVInstallation *currentInstallation = [AVInstallation currentInstallation]; // 设置deviceToken [currentInstallation setDeviceTokenFromData:deviceToken]; // 保存到LeanCloud服务器 [currentInstallation saveInBackground]; } |
如果第2步获取用户授权成功,系统会自动调用本方法,并传递APNs服务返回的deviceToken
我们通过创建AVInstallation对象,并调用setDeviceTokenFromData:方法来设置获得到的deviceToken
并需要保存deviceToken (saveInBackground方法).
4.订阅频道
1 | AVInstallation *currentInstallation = [AVInstallation currentInstallation]; // 订阅"Giants"频道 [currentInstallation removeObject:@"Giants" forKey:@"channels"]; // 保存订阅 [currentInstallation saveInBackground]; |
订阅某个频道后,发送消息的时候指定要发送的频道即可.
频道类似将用户分成组别,订阅频道就相当于用户加入到消息组中,向频道发送消息后,该频道的用户都可以收到消息.
5.发送消息到频道
因默认情况,LeanCloud认为从客户端发起的推送都使用发布证书,测试中我们需要使用测试证书,必须调用下面的方法进行设置
1 | // NO: 使用测试证书 // 默认值为YES: 使用发布证书 [AVPush setProductionMode:NO]; |
发送消息到频道
1 | // 创建发布消息对象 AVPush *push = [[AVPush alloc] init]; // 设置发布频道 [push setChannel:@"Giants"]; // 设置消息 [push setMessage:@"The Giants just scored!"]; // 发送消息 [push sendPushInBackground]; |
订阅了频道的设备才能收到消息.
6.接收推送到的消息
- 应用在前台运行中,收到消息后,系统会自动调用下面方法
1 | - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo |
- 应用在后台或者应用未启动,点击通知后,相当于直接点击应用图标操作,系统调用下面的方法
1 | application:didFinishLaunchingWithOptions:(NSDictionary *)launchOptions |
点击图标启动和点击通知消息启动的区别:
点击图标启动应用时,参数launchOptions的值为nil
点击通知消息启动应用时,参数launchOptions的值就是消息数据体
7.退订消息
1 | AVInstallation *currentInstallation = [AVInstallation currentInstallation]; [currentInstallation removeObject:@"Giants" forKey:@"channels"]; [currentInstallation saveInBackground]; |
退订后,设备将不再接受该频道的推送消息