函数不会等到数据下载完成 [英] Function does not wait until the data is downloaded

查看:50
本文介绍了函数不会等到数据下载完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能可以从服务器下载图像;

I have the following function which downloads an image from server;

func getImageFromServerById(imageId: String) -> UIImage? {
    let url:String = "https://dummyUrl.com/\(imageId).jpg"
    var resultInNSDataformat: NSData!

    let task = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) {(data, response, error) in
        if (error == nil){
            resultInNSDataformat = data
        }
    }
    task.resume()
    return UIImage(data: resultInNSDataformat)
}

该函数不会等待下载任务完成才返回图像.因此我的应用程序总是崩溃.关于如何等待下载的任何想法?

The function does not wait for the download task to be completed before returning the image. Therefore my app always crashes. Any ideas for how to wait for the download?

推荐答案

另一个答案并不能很好地替代您已有的代码.更好的方法是继续使用 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
    }
}

这篇关于函数不会等到数据下载完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆