当我的应用进入后台时,AppDelegate未侦听来自APNS的新推送通知。但奇怪的是,它不会一直发生。有时它起作用,有时它不起作用。我无法弄清楚为什么。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];
}
服务器端发送通知内容可用:1和应用程序应该从服务器获取数据。但是,didReceiveRemoteNotification没有被调用 - 但它并不是一直发生的。有时候,它可以工作。我不明白这一点。顺便说一句,谢谢你的回复。 – user3781953 2014-10-08 09:08:17
didReceiveRemoteNotification将只在应用程序处于运行状态且没有代码在后台状态下执行时调用。如何了解某个时间其工作? – 2014-10-08 09:32:24
我把日志行放在applicationDidEnterBackground中,这样我就知道应用何时进入后台状态。并且在didReceiveRemoteNotification中有一个日志行来打印通知,有时我可以在日志中看到通知。 – user3781953 2014-10-08 10:06:52