代码之家  ›  专栏  ›  技术社区  ›  Vahid

Swift后台数据任务

  •  1
  • Vahid  · 技术社区  · 8 年前

    我想用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()
    

    这仍然只在前台工作。

    我错过了什么?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Martin Prusa    8 年前

    你需要实施 AppDelegate 方法

    把这个交给你的代表

    另外,您应该实现 背景模式 . 你的问题的相对答案可以在这里找到。 URLSession.datatask with request block not called in background