In didFinishLaunchingWithOptions
调用函数的定时器循环httpRequest
每 1 分钟间隔一次。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//rest of code
NSTimer *notifyTimer = [NSTimer timerWithTimeInterval:60 target:self selector:@selector(httpRequest) userInfo:nil repeats:YES];//7200.0
[[NSRunLoop mainRunLoop] addTimer:notifyTimer forMode:NSDefaultRunLoopMode];
return YES;
}
按主页按钮后应用程序将进入后台并调用功能applicationDidEnterBackground
所以后台任务正在启动。
- (void)applicationDidEnterBackground:(UIApplication *)application
{
__block UIBackgroundTaskIdentifier bgTask;
UIApplication *app = [UIApplication sharedApplication];
expirationHandler = ^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
bgTask = [app beginBackgroundTaskWithExpirationHandler:expirationHandler];
};
bgTask = UIBackgroundTaskInvalid;
bgTask = [app beginBackgroundTaskWithExpirationHandler:expirationHandler];
}
By httpRequest
我得到的功能Y
每 1 分钟间隔从 Web 服务器发送一次UILocalNotification
每秒触发一次。
-(NSString *)httpRequest {
NSURL *url = [NSURL URLWithString:@"http://192.168.10.67/t.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *userAgent = [NSString stringWithFormat:@"bgTaskTest-IOS"];
[request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPMethod:@"GET"];
[request setTimeoutInterval:25];
NSURLResponse *response;
NSData *dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *stringReply = [[NSString alloc] initWithData:dataReply encoding:NSASCIIStringEncoding];
if ([stringReply isEqualToString:@"Y"]) {
[self showLocalNotification:nil]; //calling UILocalNotification
} else {
NSLog(@"%@",stringReply);
}
return stringReply;
}
功能showLocalNotification
根据响应每 1 分钟调用一次httpRequest
功能。
-(void)showLocalNotification {
NSString *msg = @"test message";
[[UIApplication sharedApplication] cancelAllLocalNotifications];
UILocalNotification *_localNotification = [[UILocalNotification alloc]init];
_localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
_localNotification.timeZone = [NSTimeZone defaultTimeZone];
_localNotification.alertBody = msg;
_localNotification.soundName = UILocalNotificationDefaultSoundName;
_localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber]+1;
[[UIApplication sharedApplication] scheduleLocalNotification:_localNotification];
//[[UIApplication sharedApplication] presentLocalNotificationNow:_localNotification];
}
一切正常,当应用程序在后台时,每 1 分钟就会提示一次通知。
但我的问题是后台任务的生命周期是10分钟,所以10分钟后没有通知提示。因此,我再次开始后台任务beginBackgroundTaskWithExpirationHandler
但我的应用程序在重新启动后台任务时被终止。
当应用程序处于后台时,我无法使用通知超过 10 分钟。
请任何人帮助我。