7

使用 XCode-8.2.1、Swift-3.0.2 和 iOS-10.2.1,

我正在尝试调用两个不同的 URLSession.shared.dataTasks(第一个是简单的 URL 请求,第二个是 POST 请求)。

由于我的第一个 dataTask 提供了第二个 dataTask 的 httpBody 中需要的结果,因此两个 URLSession.shared.dataTask 应该一个接一个地连续运行!(并且准备代码应连续运行)。

到目前为止,我尝试使用两个连续serialQueue.sync{}的队列。但我不得不意识到代码并没有按照我想要的顺序执行。

日志中的打印语句结果如下:

Hmmmmmm 2
Hmmmmmm 1
Hmmmmmm 3

(根据需要而不是 1、2、3)!

你怎么能得到订单1、2、3??

(即如何确保第二个 dataTask 的 httpBody 可以填充来自第一个 dataTask 的结果?

这是我的代码:(不可执行,因为 URL 已被删除 - 但你明白了)!

import UIKit

class ViewController: UIViewController {

    let serialQueue = DispatchQueue(label: "myResourceQueue")
    var stationID: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


        self.serialQueue.sync {
            let myResourceURL = URL(string: "myQueryString1")
            let task = URLSession.shared.dataTask(with: myResourceURL!) { (data, response, error) in
                if (error != nil) {
                    // print(error.debugDescription)
                } else {
                    if let myData = data {
                        do {
                            let myJson = try JSONSerialization.jsonObject(with: myData, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                            // print(myJson)
                            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                            print("Hmmmmmm 1")
                            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                        } catch {
                            // error
                        }
                    }
                }
            }
            task.resume()
        }
        self.serialQueue.sync {
            var request = URLRequest(url: URL(string: "myQueryString2")!)
            request.httpMethod = "POST"
            request.addValue("API_id", forHTTPHeaderField: "Authorization")
            request.addValue("application/xml", forHTTPHeaderField: "Content-Type")
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            print("Hmmmmmm 2")
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            let postString: String = "My_XML_POST_Body"
            request.httpBody = postString.data(using: .utf8)
            let task = URLSession.shared.dataTask(with: request) { data, response, error in
                // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                print("Hmmmmmm 3")
                // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            }
            task.resume()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

任何帮助表示赞赏!

4

2 回答 2

4

我终于找到了解决方案:

这个答案的启发,我介绍了一个URLSessionDataDelegate, 以及它的委托回调方法(即didReceive response:,didReceive data:didCompleteWithError error:.

重要提示:您需要使用委托设置 URLSession,以使引入的 URLSessionDelegate 的回调方法起作用:使用 URLSession(configuration: ....) 如下所示:

let URLSessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: URLSessionConfig, delegate: self, delegateQueue: OperationQueue.main)

之后,您就可以开始了,即日志现在符合预期:

Hmmmmmm 1
Hmmmmmm 2
Hmmmmmm 3

这是最终代码(同样不可执行,因为 URL 已被删除 - 但你明白了)!

import UIKit

class ViewController: UIViewController, URLSessionDataDelegate {

    var stationID: Int = 0
    let URLSessionConfig = URLSessionConfiguration.default
    var session: URLSession?
    var task1: URLSessionTask?
    var task2: URLSessionTask?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.session = URLSession(configuration: URLSessionConfig, delegate: self, delegateQueue: OperationQueue.main)

        // prepare dataTask Nr 1
        let myResourceURL = URL(string: "myQueryString1")
        self.task1 = session?.dataTask(with: myResourceURL!)

        // start dataTask Nr 1 (URL-request)
        self.task1?.resume()
    }

    // Optional: Use this method if you want to get a response-size information 
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {

        // print(Int(response.expectedContentLength))
        completionHandler(URLSession.ResponseDisposition.allow)
    }

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {

        if dataTask == self.task1 {
           do {
              let myJson = try JSONSerialization.jsonObject(with: myData, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
              // print(myJson)
              // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
              print("Hmmmmmm 1")
              // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

              // prepare dataTask Nr 2
              self.task2 = self.session?.dataTask(with: self.prepareMyURLRequest())
           } catch {
              // error
           }
        } else if dataTask == self.task2 {

            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            print("Hmmmmmm 3")
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

        } else {
            print("unknown dataTask callback")
        }
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
       if (error != nil) {
          // print(error.debugDescription)
       } else if task == self.task1 {

          // start dataTask Nr 2 (POST URL-request)
          self.task2?.resume()
       }
    }

    func prepareMyURLRequest() -> URLRequest {
        var request = URLRequest(url: URL(string: "myQueryString2")!)
        request.httpMethod = "POST"
        request.addValue("API_id", forHTTPHeaderField: "Authorization")
        request.addValue("application/xml", forHTTPHeaderField: "Content-Type")
        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        print("Hmmmmmm 2")
        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        let postString: String = "My_XML_POST_Body"
        request.httpBody = postString.data(using: .utf8)
        return request
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
于 2017-02-06T20:19:02.220 回答
1

如果 task2 需要 task1 的结果,您应该从 task1 的完成块启动 task2

URLSession.shared.dataTask(with: request) { data, response, error in
    // process task1 and setup request2
    URLSession.shared.dataTask(with: request2) { data, response, error in
        // process task2
    }.resume()
}.resume()

当然,这对于多个请求会变得有点笨拙,所以使用 Promises & Futures 可能会更好。Swift 有几种 Promises & Futures 的实现,例如Promis

于 2018-05-05T15:41:47.807 回答