我已經(幾乎)成功實現了URLSessionDelegate
,URLSessionTaskDelegate
和URLSessionDataDelegate
,以便我可以在後臺上傳我的對象。但我不知道如何實現完成處理程序,這樣我可以刪除我發送的對象,當服務器返回statuscode=200
實現backgroundSession.uploadTask的完成處理程序
我現在開始uploadTask
這樣
let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.myObject\(myObject.id)")
let backgroundSession = URLSession(configuration: configuration,
delegate: CustomDelegate.sharedInstance,
delegateQueue: nil)
let url: NSURL = NSURL(string: "https://www.myurl.com")!
let urlRequest = NSMutableURLRequest(url: url as URL)
urlRequest.httpMethod = "POST"
urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let uploadTask = backgroundSession.uploadTask(with: urlRequest as URLRequest, fromFile: path)
uploadTask.resume()
我嘗試添加一個關閉到uploadTask
的初始化,但xcode顯示一個錯誤,這是不可能的。
我有我的自定義類CustomDelegate:
class CustomDelegate : NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate {
static var sharedInstance = CustomDelegate()
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
print("\(session.configuration.identifier!) received data: \(data)")
do {
let parsedData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
let status = parsedData["status"] as! NSDictionary
let statusCode = status["httpCode"] as! Int
switch statusCode {
case 200:
// Do something
case 400:
// Do something
case 401:
// Do something
case 403:
// Do something
default:
// Do something
}
}
catch {
print("Error parsing response")
}
}
}
它還實現了與會代表的其他功能。
我想知道的是,上傳完成後,我可以從CustomDelegate
內更新我覺得很難(也許不可能?)的用戶界面和數據庫。
實現['didCompleteWithError'](https://developer.apple.com/reference/foundation/urlsessiontaskdelegate/1411610-urlsession)。如果你想進度更新,你可以使用['didSendBodyData'](https://developer.apple.com/reference/foundation/urlsessiontaskdelegate/1408299-urlsession)。 – Rob
不相關,但不是實例化NSURL和NSMutableURLRequest並轉換爲URL和URLRequest,你應該首先創建URL和URLRequest。唯一的竅門是,既然你想改變'URLRequest',使用'var',而不是'let'。 – Rob
@Rob我已經這樣做了,但我的問題是如何「擺脫」CustomDelegate類。如果我例如在'mainViewController'中,並且調用一個執行'uploadTask'設置的函數,那麼我想更新UI,例如 – Frederik