在Swift 3上运行后台线程

FS.*_*.O6 26 iphone cocoa-touch ios swift swift3

我有一个像这样的函数:

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)!)
}
Run Code Online (Sandbox Code Playgroud)

我想在一个上运行它Background thread.

我已经尝试了这些GDC方法Swift2,但它没有用.

线程主题中有什么变化Swift3吗?

谢谢!

Max*_*ner 59

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

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)!)
            }
        })
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

斯威夫特 4.0

func setupImageViewWithURL(url: URL) {

    var image: UIImage? = nil
    DispatchQueue.global(qos: .background).async {
        do {
            try image = UIImage(data: Data(contentsOf: url))!
        } catch {
            print("Failed")
        }
        DispatchQueue.main.async {
            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)!)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案添加到已经接受的答案中是什么?对我来说,这只是一个更改最少的复制粘贴。 (2认同)