didFinishLaunchingWithOptions
定時器循環每隔1分鐘調用一個函數httpRequest
。UILocalNotification在背景10分鐘後沒有提示
- (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;
}
按home鍵的應用程序將背景和調用函數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
功能我從Web服務器每秒鐘經過這麼一個UILocalNotification
火災每1分鐘間隔之後歌廳Y
。
-(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
基於httpRequest
函數的響應每1分鐘後調用。
-(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分鐘的通知。
請有人幫助我。