Run a background thread on Swift 3

后端 未结 3 945
情书的邮戳
情书的邮戳 2021-02-01 17:19

I have a function that goes like this:

fileprivate func setupImageViewWithURL(url: URL) {
    var image: UIImage? = nil
    do {
        try image = UIImage(data         


        
相关标签:
3条回答
  • 2021-02-01 17:37

    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)!)
                }
            })
        }
    }
    
    0 讨论(0)
  • 2021-02-01 17:40

    Swift 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)!)
                }
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-01 17:44

    DispatchQueue.global(qos: .background).async {

    }

    0 讨论(0)
提交回复
热议问题