iOS推送相关

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];
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,133评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,682评论 3 390
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,784评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,508评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,603评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,607评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,604评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,359评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,805评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,121评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,280评论 1 344
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,959评论 5 339
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,588评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,206评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,442评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,193评论 2 367
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,144评论 2 352

推荐阅读更多精彩内容