我正在尝试在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()
这仍然仅在前台有效。
我在这里想念什么?
答案 0 :(得分:1)
您将需要实现AppDelegate
方法
并将其发送给您的代表
此外,您应该实现后台模式。在这里可以找到您问题的相对答案。 URLSession.datatask with request block not called in background