可在应用后台执行时,本地弹出推送通知,也可以定时触发推送。
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UIDevice* device = [UIDevice currentDevice];
BOOL backgroundSupported = NO;
if ([device respondsToSelector:@selector(isMultitaskingSupported)])
{
backgroundSupported = device.multitaskingSupported;
}
if (backgroundSupported && _bgTask==UIBackgroundTaskInvalid)
{
UIApplication *app = [UIApplication sharedApplication];
_bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
}];
dispatch_async(dispatch_get_main_queue(), ^{
while (app.applicationState==UIApplicationStateBackground && _bgTask!=UIBackgroundTaskInvalid && [app backgroundTimeRemaining] > 10)
{
[NSThread sleepForTimeInterval:1];
NSLog(@"background task %d left left time %d.", _bgTask, (int)[app backgroundTimeRemaining]);
if ([app backgroundTimeRemaining] < 580)
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif)
{
localNotif.alertBody = [NSString stringWithString:@"测试本地通知消息,后台提示功能。"];
localNotif.alertAction = NSLocalizedString(@"查看", nil);
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
[application presentLocalNotificationNow:localNotif];
[localNotif release];
break;
}
}
}
NSLog(@"background task %d finished.", _bgTask);
[app endBackgroundTask:_bgTask];
_bgTask = UIBackgroundTaskInvalid;
});
}
}