iOS开发笔记 | 远程推送相关
2019-02-25 本文已影响6人
无夜之星辰

APP的三种状态
-
APP未运行
-
APP在后台运行
-
APP在前台运行
不同状态接收到通知时的表现
当APP在前台运行时,收到推送消息不会展示通知框。
当APP未运行或在后台运行时,收到推送消息会展示通知框。
方法回调的时机
如果APP在前台,收到推送通知时,立即回调:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler NS_AVAILABLE_IOS(7_0);
如果APP在后台,接收到通知时并不会立即回调上述方法,而是点击通知框进入APP后才回调。
APP未运行时同理。
两种情况
可以把方法的调用分为前台调用和非前台调用,需要分别对这两种情况做不同的处理。一般在前台收到推送通知会根据产品需求展示一个自定义的toast。
参考代码
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
// 信鸽推送相关
[[XGPush defaultManager] setXgApplicationBadgeNumber:1];
[[XGPush defaultManager] reportXGNotificationInfo:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
NSMutableDictionary *mutableInfo = [NSMutableDictionary dictionaryWithDictionary:userInfo];
// 是否在前台
NSNumber *isActive = nil;
UIApplicationState state = [UIApplication sharedApplication].applicationState;
if (state == UIApplicationStateActive) {
// 在前台
isActive = [NSNumber numberWithBool:YES];
} else {
// 不在前台
isActive = [NSNumber numberWithBool:NO];
}
[mutableInfo setObject:isActive forKey:@"isActive"];
// 发送通知(这里延迟0.5秒是为了避免点击通知框时APP是未运行状态,主页还未完成初始化无法接收通知)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:CQAppDidReceiveJumpPushNotification object:nil userInfo:mutableInfo];
});
}
经验之谈(自己手动测试的。。。)
注:我用的是信鸽推送,不同的SDK有可能表现不同。
-
先登陆账号A,这个时候token跟A绑定,如果这个时候没有将token与A解绑,直接登陆账号B,这个时候token还会与B绑定。推送消息给A或B,设备都会收到推送消息。(不过未解绑就登录另一个账号,这种操作就不严谨)
-
先在手机A上登陆user,再在手机B上登陆同一个user,向user推送消息,只有手机B能收到消息。
-
先在手机A上登陆user,再在手机B上登陆同一个user,任意一个手机解绑,两个手机都不能接收到给user的推送。(就是这么神奇)