我在我当前的一个项目中设置了推送通知.我已经按照推送通知所需的所有指令.在[tag:ios7]中正常工作,但在7.1中,当我的应用程序处于后台模式时,我在徽章更新中遇到问题.
我的代码如下: –
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)]; } - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error { NSLog(@"Failed to get token,error: %@",error); } - (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDevicetoken:(NSData*)devicetoken { Nsstring *str = [Nsstring stringWithFormat:@"%@",devicetoken]; NSLog(@"%@",str); self.devicetoken = [Nsstring stringWithFormat:@"%@",str]; NSLog(@"dev --- %@",self.devicetoken); self.devicetoken = [self.devicetoken stringByReplacingOccurrencesOfString:@"<" withString:@""]; self.devicetoken = [self.devicetoken stringByReplacingOccurrencesOfString:@" " withString:@""]; self.devicetoken = [self.devicetoken stringByReplacingOccurrencesOfString:@">" withString:@""]; NSLog(@"dev --- %@",self.devicetoken); }
并获得回应
-(void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo { UIApplicationState state = [application applicationState]; // If your app is running if (state == UIApplicationStateActive) { //You need to customize your alert by yourself for this situation. For ex,Nsstring *cancelTitle = @"ok"; // Nsstring *showTitle = @"Get Photos"; Nsstring *message = [[userInfo valueForKey:@"aps"] valueForKey:@"alert"]; UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:message delegate:self cancelButtonTitle:cancelTitle otherButtonTitles:nil]; [alertView show]; } // If your app was in in active state else if (state == UIApplicationStateInactive) { } [UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber + [[[userInfo objectForKey:@"aps"] objectForKey: @"badge"] intValue]; }
第一件事是,当我的应用程序回到地面时,didReceiveRemoteNotification没有被调用,所以我做了一些搜索并放置: –
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
并将背景模式设置为: –
当我的设备连接xcode并运行应用程序测试推送通知但是当我拔掉设备(iOS7.1)时,一切正常.然后推送通知到达但徽章没有更新.否则,徽章会在后台更新,也会调用所有方法.但同样的事情我测试这个应用程序到我的另一台iOS7设备,运行良好.
解决方法
尝试:
int badge = [UIApplication sharedApplication].applicationIconBadgeNumber; [UIApplication sharedApplication].applicationIconBadgeNumber = 0; // try 0 or -1 [UIApplication sharedApplication].applicationIconBadgeNumber = badge + [[[userInfo objectForKey:@"aps"] objectForKey: @"badge"] intValue];