我想用Swift做一个后台发帖请求。我知道我应该配置一个后台URLSession并使用委托而不是完成处理程序。
这是我正在使用的代表:
class Delegate:NSObject, URLSessionDelegate, URLSessionTaskDelegate,
URLSessionDataDelegate{
var completionHandler:((String) -> Void)?
func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
completionHandler(URLSession.ResponseDisposition.allow)
}
func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive data: Data) {
let responseString = String(data: data, encoding: .utf8)!
if let handler = self.completionHandler {
handler(responseString)
session.finishTasksAndInvalidate()
}
}
}
这就是我启动数据任务的方式:
let url = URL(string: endpoint)
var request = URLRequest(url: url!)
request.setValue("text/xml", forHTTPHeaderField: "Content-Type")
request.httpBody = body.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
request.httpMethod = "POST"
let delegate = Delegate()
delegate.completionHandler = {
data in
// use the data
}
let config = URLSessionConfiguration.background(withIdentifier: "id-background")
let session = URLSession(configuration: config, delegate: delegate, delegateQueue: nil)
let task = session.dataTask(with: request)
task.resume()
这仍然只在前台工作。
我错过了什么?