1. 程式人生 > >IOS在後臺每隔一段時間執行一下

IOS在後臺每隔一段時間執行一下

步驟:

1.在info.plist里加入UIBackgroundModes鍵,其值為陣列,陣列之一為voip字串:

<key>UIBackgroundModes</key><array><string>voip</string></array>

2.在程式啟動的時候呼叫- (void)setupBackgroundHandler函式,函式體如下:

#pragma mark - VoIP - (void)setupBackgroundHandler {    if( UIUDeviceIsBackgroundSupported() )
{ if( [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler: ^ { [self requestServerHowManyUnreadMessages]; } ] ) { UDLog(@"Set Background handler successed!"); } else {//failed UDLog(@"Set Background handler failed!"); } } else { UDLog(@"This Deviece is not Background supported."
); } } - (void)requestServerHowManyUnreadMessages { UIApplication* app = [UIApplication sharedApplication]; if([app applicationState] == UIApplicationStateBackground) { NSArray * oldNotifications = [app scheduledLocalNotifications]; if ([oldNotifications count] > 0) [app cancelAllLocalNotifications];
UILocalNotification* alarm = [[[UILocalNotification alloc] init] autorelease]; if (alarm) { alarm.fireDate = [NSDate dateWithTimeIntervalSinceNow:15]; alarm.timeZone = [NSTimeZone defaultTimeZone]; alarm.repeatInterval = 0; alarm.soundName = UILocalNotificationDefaultSoundName; alarm.alertBody = @"Time to request MOA2 Server!"; [app scheduleLocalNotification:alarm]; } } else if([app applicationState] == UIApplicationStateActive) { UIAlertView *alertView =  [[[UIAlertView alloc] init] autorelease]; [alertView setTitle:@"alert"]; [alertView setMessage:@"Time to request MOA2 Server!"]; [alertView addButtonWithTitle:NSLocalizedString(@"cancel", nil)]; [alertView setDelegate:nil]; [alertView show]; } }

解說:


- (BOOL)setKeepAliveTimeout:(NSTimeInterval)timeout handler:(void (^)(void))keepAliveHandler

函式功能:app每隔timeout喚醒一次。

0.要成功呼叫該函式,就必須在Info.plist裡設UIBackgroundModes鍵的array值之一voip字串.

1.timeout必須>=600

2.喚醒app的時間間隔是不精準的。

3.喚醒後只有10秒執行時間。即handler裡的程式碼要在10秒類執行完。10秒後app再次被阻塞。

(可以用-backgroundTimeRemaining屬性來返回剩餘時間

4.該函式成功呼叫後,在程式生命週期內有效。

該函式的效果在回到前臺的狀況下,依然有效。(因此可以把它當timer使.) 

5.clearKeepAliveTimeout函式用來清除handler。