2014-02-23 31 views
2
  • 我正在爲我的項目使用AFNetworking 2.0。很簡單,我只是 發送一些請求到服務器和服務器返回一些JSON爲 我。
  • 爲了測試它,我在 AFNetworking POST方法的成功塊中標記了一些調試標記。問題是前臺應用程序處於 時,應用程序收到來自服務器的響應時, xCode可以停止在成功和失敗塊中的調試標記處。 但是,當我提出請求後,將應用程序置於後臺(按 主頁按鈕),調試永遠不會進入塊。
  • 看起來他們在應用程序在後臺時暫停,因爲 當應用程序再次在前臺時,調試立即進入 該塊,我得到了迴應。

我這麼想嗎?因爲我希望應用程序能夠收到響應並執行一些操作,即使它在後臺也是如此。 這裏是我在我的應用程序中使用:AFNetworking 2.0 - 請求在後臺應用程序不進入成功塊

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
NSDictionary *parameters = /*generate the parameters*/; 
NSURL *filePath = [NSURL fileURLWithPath:@"imageName.png"]; 
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
    [formData appendPartWithFileURL:filePath name:@"image" error:nil]; 
} success:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSLog(@"Success: %@", responseObject); 

//debug here 
//Told the app to stop the Loading View, save response to DB 

} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"Error: %@", error); 

//debug here 
//Told the app to stop the Loading View and try again sometimes 

}]; 

回答

6

這是我的壞。我忘了告訴應用程序在進入後臺時繼續運行。我添加這些代碼到我的項目:

UIBackgroundTaskIdentifier backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ 
    [[UIApplication sharedApplication] endBackgroundTask:backgroundTask]; 
}]; 

當應用程序進入背景:

[[UIApplicatioz sharedApplication] endBackgroundTask:backgroundTask]; 
1

你Appdelegate.m頂部定義UIBackgroundTaskIdentifier文件

UIBackgroundTaskIdentifier bgTask = 0; 

,然後在你的

  • (無效)applicationDidEnterBackground:(UIApplication的*)應用

函數中添加以下

bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ 
    bgTask = UIBackgroundTaskInvalid; 
}]; 

的代碼應該看到這樣的:

- (void)applicationDidEnterBackground:(UIApplication *)application 
{   
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ 
     bgTask = UIBackgroundTaskInvalid; 
    }]; 
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 
} 
+0

是否需要「背景應用程序刷新「由用戶啓用? –

相關問題