在Swift 3上运行后台线程 [英] Run a background thread on Swift 3

查看:532
本文介绍了在Swift 3上运行后台线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的函数:

fileprivate func setupImageViewWithURL(url: URL) {
    var image: UIImage? = nil
    do {
        try image = UIImage(data: Data(contentsOf: url))!
    } catch is NSError {
        print("Failed")
    }

    image = self.imageWithImage(sourceImage: image!, scaledToWidth: UIScreen.main.bounds.size.width)
    self.imageImageView.image = image
    self.imageImageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: (image?.size.height)!)
}

我想在上面运行它a 背景 线程

I want to run it on a Background thread.

我试过了 GDC Swift2 的方法,但它没有用。

I've tried the GDC methods of Swift2 but it didn't worked.

Swift3 中的主题话题有什么变化吗?

Did anything changed on the thread topic in Swift3?

谢谢!

推荐答案

可以在后台加载图像,但在后台线程上执行UI更新是不行的。这就是函数必须包含两个线程的原因。

It's OK to load image on the background, but it's not OK to perform UI updates on background thread. That's why the function must contain two threads.

func setupImageViewWithURL(url: URL) {
    var image: UIImage? = nil

    DispatchQueue.global().async { 
        do {
            try image = UIImage(data: Data(contentsOf: url))!
        } catch {
            print("Failed")
        }
        DispatchQueue.main.async(execute: {
            if image != nil {
                image = self.imageWithImage(sourceImage: image!, scaledToWidth: UIScreen.main.bounds.size.width)
                self.imageImageView.image = image
                self.imageImageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: (image?.size.height)!)
            }
        })
    }
}

这篇关于在Swift 3上运行后台线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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