2016-11-19 26 views
0

我有以下代碼在應用即將退出之前調用服務器。我的問題是,代碼有時起作用,有時不起作用。大部分不是。這裏是代碼:backgroundTask未在iOS中完成

//Set the user as in-active if app is force closed 
- (void)applicationWillTerminate:(UIApplication *)application { 
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 

    NSLog(@"called"); 

    bgTask = [application beginBackgroundTaskWithName:@"setInActive" expirationHandler:^{ 
     [application endBackgroundTask:bgTask]; 
     bgTask = UIBackgroundTaskInvalid; 

    }]; 

    // Start the long-running task and return immediately. 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 

     NSLog(@"disp called"); 

     //If the app is about to exit make the user inactive 
     [[APIManager sharedInstance] setInActiveOnCompletion:^(BOOL finished){ 
      [application endBackgroundTask:bgTask]; 
      bgTask = UIBackgroundTaskInvalid; 
     }]; 

    }); 

} 

每次都會調用第一個NSLog。然而第二個沒有。這似乎應用程序甚至沒有進入dispatch_async方法。

編輯:所以基本上我所需要做的就是告訴服務器,用戶強制退出應用程序,而該用戶登錄。我怎麼能這樣做?

任何想法?

回答

0

applicationWillTerminate是在應用程序終止前被調用的最後一個方法!因此,如果您想在後臺執行某些操作,然後在執行操作時開始執行此任務,則無法執行任何操作,因此您無法從applicationWillTerminate開始background task,因爲在此方法調用之後,您的應用將不在後臺! !

0

當你的應用程序在後臺時,它只允許處理很少的數據,因此使用dispatch_async不會爲你多花費額外的時間。另外,Apple不希望這樣。