2014-10-19 60 views
2

我有問題使用AFURLSessionManager實現後臺任務。 我正在用BaseURL和SessionConfiguration創建一個新的AFHTTPSessionManager,使用NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:並使用便捷方法創建POST請求。使用AFNetworking 2.0與後臺任務

當我運行我的應用程序時,第一個請求會正常發送,但第二個請求會返回A background URLSession with identifier {ID} already exists!,並且會使應用程序崩潰。

我看過蘋果的WWDC 2013條的視頻,他們建議你創建會話配置只有一次,用

dispatch_once(&onceToken, ^{ 
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.yourcompany.appId.BackgroundSession"]; 
    session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; 
}); 

然而,有session屬性AFURLSessionManager被設置爲只讀,沒有辦法,我通過自定義NSURLSession,只有NSURLSessionConfiguration,那就是裏面AFURLSessionManager:init創建:

self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue]; 

我覺得我做錯了什麼,但我還能怎麼支持後臺任務使用AFNetworking?

回答

2

您無法實例化新的AFHTTPSessionManager,然後將它的session更改爲引用某個單例NSURLSession是正確的。因此,您應該使AFHTTPSessionManager對象本身成爲可在整個應用程序中重用的共享實例。

end of this answer,我提供了一個AFNetworking用於後臺會話的例子。

+0

我應該在任何時候調用invalidateAndCancel? – 2014-10-19 21:14:52

+0

我想你可以,但除非有令人信服的需求,否則我不會打擾。感覺像過早優化我... – Rob 2014-10-19 21:42:25

+0

晚評論:我的應用程序使用共享的'AFHTTPSessionManager'對象定期下載(用戶提示),我想添加後臺更新。我應該爲此創建另一個「AFHTTPSessionManager」嗎?或者是否可以在運行中更改'NSURLSessionConfiguration'? – Koen 2016-03-24 12:24:23