在每 1 分钟间隔didFinishLaunchingWithOptions
调用一个函数的计时器循环中。httpRequest
- (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];
}
通过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 分钟的通知。
请任何人帮助我。