iOS推送相关

2018-09-07  本文已影响0人  编程猫猫

1、清除推送的badgeNumber

在bugtags后台bug时发现,有用户因为下面的代码,而崩溃。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[YKPushManager shareYKPushManager] yk_initJpushServiceWithOptions:launchOptions];   //推送
   [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    return YES;
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
   [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

查找原因得知

 // set to 0 to hide. default is 0. In iOS 8.0 and later, your application must register for user notifications using -[UIApplication registerUserNotificationSettings:] before being able to set the icon badge.

意思是要先注册推送,才能设置角标,可是我注册了推送啊,what?这是什么原因?!

后来发现是设置角标的写法有问题,正确的写法是:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[YKPushManager shareYKPushManager] yk_initJpushServiceWithOptions:launchOptions];   //推送
    [self resetBageNumber];
    return YES;
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
  [self resetBageNumber];
}
- (void)resetBageNumber
{
    if ([UIApplication sharedApplication].applicationIconBadgeNumber > 0) {
        if (@available(iOS 11.0, *)) {
            [UIApplication sharedApplication].applicationIconBadgeNumber = -1;
        } else {
            UILocalNotification *localNotification = [[UILocalNotification alloc] init];
            localNotification.fireDate = [NSDate date];
            localNotification.applicationIconBadgeNumber = -1;
            [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
        }
    }
}

后来有发现了一个问题,如上设置之后,还有点小问题。就是点一下, 其他推送的消息也不见了,这样角标数量 不太正确 ,进来就给清了,但是呢,但是推送信息还在。

故又做了如下的修改:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
   [[YKPushManager shareYKPushManager] yk_initJpushServiceWithOptions:launchOptions];   //推送

    [self setPushBageNumberWith:launchOptions];
    return YES;
}
- (void)setPushBageNumberWith:(NSDictionary *)launchOptions
{
    NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
//如果remoteNotification = nil,则表示推送没有内容,不是从推送消息点击来的
    if (remoteNotification) {
        [[YKPushManager shareYKPushManager] dealBadgeNumber:launchOptions];
    }else{
        [self resetBageNumber];
    }
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
  [self resetBageNumber];
}

下面是YKAppDelegate中推送相关的回调函数

pragma mark - 推送回调函数
// 向苹果注册推送,在调用 registerForRemoteNotificationTypes “成功”后会触发这个回调函数
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [[YKPushManager shareYKPushManager] yk_registerDeviceToken:deviceToken];
}

//此处是点击推送消息进来调用两次
- (void)handleRemoteNotification:(NSDictionary * _Nonnull)userInfo {
    NSString *msgID = [userInfo[@"_j_msgid"] stringValue];
    DLog(@"msgID == %@",msgID);
    if (![msgID isEqualToString:[YKPushManager shareYKPushManager].messageID]) {
        [[YKPushManager shareYKPushManager] yk_handleRemoteNotification:userInfo];
        [YKPushManager shareYKPushManager].messageID = msgID;
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler{
    DLog(@"收到通知: user info:%@",userInfo);
    [self handleRemoteNotification:userInfo];
    
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark -iOS 10 以前的推送系统处理方法
// 消息推送: 消息推送时应用正在运行,会进入到这里,
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    DLog(@"didReceiveRemoteNotification is %@",userInfo);
    [self handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    DLog(@"didReceiveLocalNotification received message is %@",notification);
    [[YKPushManager shareYKPushManager] yk_showLocalNotification:notification];
}

下面是YKPushManager相关方法的实现

#pragma mark 初始化APNs 初始化Jpush
- (void)yk_initJpushServiceWithOptions:(NSDictionary *)launchOptions{
    //Required
    if (@available(iOS 10.0, *)) {
        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    }
    //可以添加自定义categories
    [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                      UIUserNotificationTypeSound |
                                                      UIUserNotificationTypeAlert)
                                          categories:nil];
    
    //Required
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容,请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    
    //    * @param channel 发布渠道. 可选.
    //    * @param isProduction 是否生产环境. 如果为开发状态,设置为 NO; 如果为生产状态,应改为 YES.
    BOOL isProduction = YES;
#ifdef DEBUG
    isProduction = NO;
#else
    //    [JPUSHService setLogOFF];
#endif
    [JPUSHService setupWithOption:launchOptions
                           appKey:kJpushAppKey
                          channel:kJpushChannel
                 apsForProduction:isProduction];
}

//注册极光
- (void)yk_registerDeviceToken:(NSData *)token
{
    [JPUSHService registerDeviceToken:token];  //注册deviceToken
    [self yk_setPushAlias];
}

- (void)yk_setPushAlias
{
    if ([YKUserManager sharedUser].yk_isLogin) {
        [JPUSHService setAlias:NSString.yk_integerToString([YKUserManager sharedUser].uid)  completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            if (iResCode == 0) {
                DLog(@"别名设置成功");
            }
        } seq:1];
    }
}

//收到推送消息
- (void)yk_handleRemoteNotification:(NSDictionary *)userInfo
{
    DLog(@"aps_alert+++++++++++%@",userInfo[@"aps"][@"alert"]);
    [JPUSHService handleRemoteNotification:userInfo];
    UIApplicationState appState = [[UIApplication sharedApplication] applicationState];
    if (appState == UIApplicationStateActive) {
        QLAlert *alert = [QLAlert alert];
        [alert prepareUIWithTitle:@"" contentText:userInfo[@"aps"][@"alert"]? :@"您有一条推送通知!" buttonTitleArray:@[@"查看",@"忽略"] buttonClicked:^(NSInteger index) {
            if (index == 0) {
                //点击跳转
                [[YKJumpManager shareYKJumpManager] yk_jumpWithParamDic:userInfo];
            }
        }];
        [alert show];
    }else{
        //跳转
        [[YKJumpManager shareYKJumpManager] yk_jumpWithParamDic:userInfo];
    }
}

#pragma mark JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center
        willPresentNotification:(UNNotification *)notification
          withCompletionHandler:(void (^)(NSInteger))completionHandler API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]
        ]) {
        [JPUSHService handleRemoteNotification:userInfo];
        DLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
    }else{
        // 判断为本地通知
        DLog(@"iOS10 前台收到本地通知:{\nbody:%@,\ntitle:%@,\nsubtitle:%@,\nbadge:%@,\nsound:%@,\nuserInfo:%@\n}",body,title,subtitle,badge,sound,userInfo);
        // 更新显示的徽章个数
    }
//    NSInteger badgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber;
//    badgeNumber--;
//    badgeNumber = badgeNumber >= 0 ? badgeNumber : 0;
//    [UIApplication sharedApplication].applicationIconBadgeNumber = badgeNumber;
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive||[UIApplication sharedApplication].applicationState == UIApplicationStateBackground) {
        [self dealBadgeNumber:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert |
                      UNNotificationPresentationOptionSound |
                      UNNotificationPresentationOptionBadge);
    // 需要执 这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以选择设置
}
#pragma mark -- 推送角标处理
-(void)dealBadgeNumber:(NSDictionary*)userInfo
{
    /*
     NSInteger badge = [userInfo[@"aps"][@"badge"] integerValue];
     badge --;
     */
    NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
    badge --;
    if (badge > 0) {
        [JPUSHService setBadge:badge];
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badge];
    }else{
        if (@available(iOS 11.0, *)) {
            [JPUSHService setBadge:0];
            [UIApplication sharedApplication].applicationIconBadgeNumber = -1;
        } else {
            [JPUSHService setBadge:0];
            UILocalNotification *localNotification = [[UILocalNotification alloc] init];
            localNotification.fireDate = [NSDate date];
            localNotification.applicationIconBadgeNumber = -1;
            [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
        }
    }
}
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center
 didReceiveNotificationResponse:(UNNotificationResponse *)response
          withCompletionHandler:(void(^)())completionHandler API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(); // 系统要求执行这个方法
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive||[UIApplication sharedApplication].applicationState == UIApplicationStateBackground) {
        [self dealBadgeNumber:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)yk_deletePushAlias
{
    [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        if (iResCode == 0) {
            DLog(@"别名删除成功");
        }
    } seq:1];
}

上一篇 下一篇

猜你喜欢

热点阅读