如何解决Swift 5中的DispatchQueue问题

时间:2019-04-17 17:41:38

标签: swift xcode grand-central-dispatch

在更新Xcode和Swift 5之后,此代码不起作用。谁能告诉我如何解决?

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
    if let url  = NSURL(string: (mindata["img"] as? String)!), data = NSData(contentsOfURL: url)
    {
        dispatch_async(dispatch_get_main_queue(), {
            cell.img.image = UIImage(data: data)
        })
    }
})

1 个答案:

答案 0 :(得分:0)

您似乎正在尝试通过使用异步调度队列将图像渲染到单元格的ImageView中,对吗?如果我说的没错,您可以改用这段代码吗?

    if let url = URL(string: mindata["img"]) {
        do {
            let data = try Data(contentsOfURL: url)

            if data == nil {
                DispatchQueue.main.async {
                    cell.img.image = UIImage(data: data)
                }
            } else {
                print("Data is Nil")
            }
        } catch {
            //error from Data(contentsOfUrl to catch
        }
    } else {
        // the URL was bad!
    }

参考:https://www.hackingwithswift.com/example-code/strings/how-to-load-a-string-from-a-website-url