URLSession
數據任務塊在應用程序處於後臺時未調用,並且它在請求中停留在dataTask
。
當我打開應用程序塊被調用。順便說一句,我正在使用https
請求。
這是我的代碼:帶請求塊的URLSession.datatask在後臺未調用
let request = NSMutableURLRequest(url: URL(string: url as String)!,
cachePolicy: .reloadIgnoringCacheData,
timeoutInterval:20)
request.httpMethod = method as String
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let data = params.data(using: String.Encoding.utf8.rawValue)
request.httpBody = data
session.dataTask(with: request as URLRequest,completionHandler:
{(data, response, error) -> Void in
if error == nil
{
do {
let result = try JSONSerialization.jsonObject(with: data!, options:
JSONSerialization.ReadingOptions.mutableContainers)
print(result)
completionHandler(result as AnyObject?,nil)
}
catch let JSONError as NSError{
completionHandler(nil,JSONError.localizedDescription as NSString?)
}
}
else{
completionHandler(nil,error!.localizedDescription as NSString?)
}
}).resume()
完美的工作時,應用程序處於活動狀態。我的代碼有什麼問題嗎?請指點我
沒有關係,但爲什麼你傳遞'。 mutableContainers',但將結果分配給不可變常量?並且不要在Swift中使用'NSURLRequest'和'NSString',使用本地結構。最後,'String.Encoding.utf8.rawValue'可以寫成'.utf8',這是更少的代碼鍵入(或粘貼)。 – vadian
'會話'是後臺會話嗎?如果是這樣,請執行基於委託的下載任務,而不是數據任務。請參閱[後臺傳輸注意事項](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html#//apple_ref/doc/uid/TP40013509-SW44)。 – Rob
這意味着我可以使用下載任務eventhough沒有什麼可下載的。 –