可以使用UILocalNotification来唤醒处于后台的任务

我想知道,如果有可能以某种方式“唤醒”在后台的任务,快速检查networking上的东西..我认为这可以用UILocalNotification完成,但是,无论我尝试了什么,当应用程序在后台时,我无法得到didReceiveLocalNotification做任何事情。启动后,我立即通过按Homebuttonclosures应用程序(本地通知发生延迟10秒)。 这个代码工作完美,当应用程序在前台,只是坐在那里…

在应用程序委托头文件中:

UILocalNotification *localNotif; 

为了testing,我设置了本地通知,在appDelegate启动时快速启动。

 localNotif = [[UILocalNotification alloc] init]; localNotif.fireDate = [NSDate dateWithTimeIntervalSinceNow:10]; // the date you want the notification to fire. localNotif.timeZone = [NSTimeZone defaultTimeZone]; [[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; NSLog(@"setup the timer for 10 seconds"); - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { UIApplicationState state = [application applicationState]; NSLog(@"getting kicked"); if (state == UIApplicationStateInactive) { // Application was in the background when notification was delivered. NSLog(@"INACTIVE.."); } else { NSLog(@"ACTIVE.."); } 

}

用户有几个select:#1)他们是否想看到你的应用程序的通知。 #2)如果为您的应用程序启用了通知,他们是否想要点击您的通知来启动您的应用程序。 如果他们确实接受通知,并在应用程序处于后台时打开通知,则会调用application:didReceiveLocalNotification 。 要清楚的是,用户必须接受通知(例如滑动通知下方的滑块),否则将不会被调用。

 - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { NSLog(@"%@", notification); } 

如果您的应用程序已被终止application:didFinishLaunchingWithOptions:被调用 –

 - (BOOL)application:(UIApplication *) application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions { UILocalNotification *theNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; NSLog(@"%@", theNotification); return YES; }