当我的应用程序进入后台时,AppDelegate不会收听来自APNS的新推送通知。但奇怪的是,它并不是一直都在发生。有时候它有效,有时则不然。我无法弄清楚原因。
以下是我收听APNS通知的示例代码
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge
|UIRemoteNotificationTypeSound
|UIRemoteNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
else
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert)];
}
if (launchOptions != nil)
{
NSDictionary *dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dictionary != nil)
{
}
}
return YES;
}
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
{
NSLog(@"Received notification: %@", userInfo);
[self application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:nil];
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
NSLog(@"Received notification background: %@", userInfo);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC),
dispatch_get_main_queue(), ^{
// Check result of your operation and call completion block with the result
completionHandler(UIBackgroundFetchResultNewData);
});
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
[application registerForRemoteNotifications];
}
答案 0 :(得分:1)
在后台/关闭模式下,不会执行任何代码,也不会调用任何委托方法。此时推送通知由操作系统本身处理。应用程序徽章由来自服务器端的推送通知有效负载值设置。 如果您没有在后台获取应用程序徽章,则是服务器端的徽章编号问题。检查推送通知有效内容是否包含应用程序徽章字段并设置为大于0的值。
This link有同样的问题并解决了。
答案 1 :(得分:0)
尝试改变你的行..
if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound categories:nil]];
} else {
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound];
}
在iOS 8中你必须使用" UIUserNotificationTypeBadge" ...
希望这对你有用..