0

我对下面的代码有一些问题。虽然它有效,但存在一些时间问题。

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

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()
4

1 回答 1

1

你可以试试这个代码吗?

在第一次调用时,控件实际上不应进入处理程序内部。而且我认为您的代码中也存在一些我之前指出的错误,尤其是更新 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()
于 2017-08-16T09:41:48.183 回答