且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

函数不会等到数据下载完成

更新时间:2023-11-20 23:40:52

另一个答案并不能很好地替代您已有的代码.更好的方法是继续使用 NSURLSession 的数据任务来保持下载操作异步并将您自己的回调块添加到方法中.您需要了解在从您的方法返回之前不会执行下载任务块的内容.只需查看调用 resume() 的位置即可获得进一步的证据.

The other answer is not a good replacement for the code you already had. A better way would be to continue using NSURLSession's data tasks to keep the download operation asynchronous and adding your own callback block to the method. You need to understand that the contents of the download task's block are not executed before you return from your method. Just look at where the call to resume() is for further evidence.

相反,我推荐这样的东西:

Instead, I recommend something like this:

func getImageFromServerById(imageId: String, completion: ((image: UIImage?) -> Void)) {
    let url:String = "https://dummyUrl.com/\(imageId).jpg"

    let task = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) {(data, response, error) in
        completion(image: UIImage(data: data))
    }

    task.resume()
}

可以这样称呼

getImageFromServerById("some string") { image in
    dispatch_async(dispatch_get_main_queue()) {
        // go to something on the main thread with the image like setting to UIImageView
    }
}