iOS

iOS开发笔记 | 远程推送相关

2019-02-25  本文已影响6人  无夜之星辰
QQ飞车求带

APP的三种状态

  1. APP未运行

  2. APP在后台运行

  3. 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有可能表现不同。

上一篇 下一篇

猜你喜欢

热点阅读