2013-05-03 398 views
0

我試圖將後臺任務實現到我的應用程序。在我執行之前,我想給出一個簡單的例子,如下所示。我只是把一個櫃檯,並希望看看它是否重要。但是,它不會激發我稱爲進程的方法。我不知道我錯過了什麼。ApplicationDidEnterBackground不會觸發方法

- (void)applicationDidEnterBackground:(UIApplication *)application 
{ 
    if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking I.E iOS 4 
     if ([[UIDevice currentDevice] isMultitaskingSupported]) { //Check if device supports mulitasking 
      UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance 
      __block UIBackgroundTaskIdentifier background_task; //Create a task object 
      background_task = [application beginBackgroundTaskWithExpirationHandler:^{ 
       [application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks 
       background_task = UIBackgroundTaskInvalid; //Set the task to be invalid 
       //System will be shutting down the app at any point in time now 
      }]; 
      //Background tasks require you to use asyncrous tasks 
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
       //Perform your tasks that your application requires 
       NSLog(@"\n\nRunning in the background!\n\n"); 
       pollingTimer2 = [NSTimer scheduledTimerWithTimeInterval:0.1 
                   target:self 
                   selector:@selector(process) 
                   userInfo:nil 
                   repeats:YES]; 
       [application endBackgroundTask: background_task]; //End the task so the system knows that you are done with what you need to perform 
       background_task = UIBackgroundTaskInvalid; //Invalidate the background_task 
      }); 
     } 
    } 

} 

-(void) process 
{ 
    county= county+1; 
    NSLog(@"%d,county",county); 

} 
+1

註釋掉endBackgroundTask並嘗試 – 2013-05-03 21:25:55

+0

你有沒有把你的.plist文件中的應用程序在後臺運行= YES? – 2013-05-04 02:06:11

回答

0

使用這些代碼如下:

if ([[UIDevice currentDevice] isMultitaskingSupported]) 
{ 
     //Check if device supports mulitasking 
     UIBackgroundTaskIdentifier bgTask; 
     UIApplication *app = [UIApplication sharedApplication]; 
     bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
      [app endBackgroundTask:bgTask]; 
     }]; 
     pollingTimer2 = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(process) userInfo:nil repeats:YES]; 
} 

其工作,並進行了測試。