session.dataTask 同步问题

session.dataTask synchronization issue

我在使用下面的代码时遇到了一些问题。 虽然它有效,但存在一些时间问题。

首先让我说一下我的期望,我想当数据下载完成并且我的图像可以使用时,完成处理程序应该是 运行。但现实似乎大不相同。当我尝试它时,立即调用完成处理程序(我可以在控制台中看到 'All OK'),就好像一切都是即时的。但是图像实际上要晚得多才能显示。我错过了什么?

let imageURL = URL(string: myURLString)
session = URLSession.shared,
_ = session.dataTask(with: imageURL) {[weak self]
    (data: Data?, response: URLResponse?, error: Error?) in
    if error == nil {
        print("All OK")
        self?.theImage = UIImage(data: data!)
        self?.theView.image = self?.theImage
    } else {print(error!)}

    DispatchQueue.main.async {
        self?.activityIndicator.stopAnimating()
        self?.theView.setNeedsDisplay()
    }
    }.resume()

你能试试这个代码吗?

第一次调用时,控件不应实际进入处理程序。而且我认为您的代码中也存在一些我之前指出的错误,尤其是 更新 UI.

需要主线程
    let session : URLSession
    let config = URLSessionConfiguration.default
    var resultFromServer: Any?
    let responseResultData = [String:Any]()
    session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
    session.dataTask(with: request) { (data, response, error ) in

        if error != nil {

            DispatchQueue.main.async(execute: {

                session.invalidateAndCancel()

            })

        }else{

            let httpResponse: HTTPURLResponse = response as! HTTPURLResponse

                do{

                    resultFromServer = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
                    if httpResponse.statusCode == 200  || httpResponse.statusCode == 201 || httpResponse.statusCode == 202 || httpResponse.statusCode == 204 || httpResponse.statusCode == 203 {

                        if let respArr = resultFromServer as? [Any]{

                          //resp is array


                        }else if let respdict = resultFromServer as? [String : Any] {

                            //resp is dict


                        }else{

                           //resp is something else maybe string, etc

                        }

                    }
                    else {


                       //error status code something like 500, 404, etc

                    }


                }

                catch let error as NSError {

                    DispatchQueue.main.async(execute: {

                        session.invalidateAndCancel()

                    })
                }

            }

        session.finishTasksAndInvalidate()
        }.resume()