使用GCD在Swift 3中进行多线程处理

时间:2017-02-21 03:32:39

标签: multithreading swift3

我正在开发一个基于Web服务的应用程序,而且由于向Web服务发送请求太快,我已经陷入了崩溃的困境。我根本无法让GCD在Swift 3中工作,而且我在摸不着头脑。我决定将其愚蠢,然后尝试按顺序将4个Web图像加载到Web视图中。基于我在网上看到的所有内容,以下代码应该可以正常工作,但是在所有四个图像加载之前,它仍然会冻结UI。我做错了什么?

import UIKit

let imageURLs = ["http://www.planetware.com/photos-large/F/france-paris-eiffel-tower.jpg", "http://adriatic-lines.com/wp-content/uploads/2015/04/canal-of-Venice.jpg", "http://hd-wall-papers.com/images/wallpapers/hi-resolution-pictures/hi-resolution-pictures-5.jpg", "http://hd-wall-papers.com/images/wallpapers/hi-resolution-pictures/hi-resolution-pictures-1.jpg"]

class Downloader {

class func downloadImageWithURL(_ url:String) -> UIImage! {

    let data = try? Data(contentsOf: URL(string: url)!)
    return UIImage(data: data!)
    }
}

class ViewController: UIViewController {

@IBOutlet weak var imageView1: UIImageView!

@IBOutlet weak var imageView2: UIImageView!

@IBOutlet weak var imageView3: UIImageView!

@IBOutlet weak var imageView4: UIImageView!

@IBOutlet weak var sliderValueLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func didClickOnStart(_ sender: AnyObject) {
    let serialQueue = DispatchQueue(label: "syncQueue")

    serialQueue.sync{
        let img1 = Downloader.downloadImageWithURL(imageURLs[0])
        DispatchQueue.main.async(execute: {

            self.imageView1.image = img1
        })
    }

    serialQueue.sync{
        let img2 = Downloader.downloadImageWithURL(imageURLs[1])
        DispatchQueue.main.async(execute: {

            self.imageView2.image = img2
        })
    }

    serialQueue.sync{
        let img3 = Downloader.downloadImageWithURL(imageURLs[2])
        DispatchQueue.main.async(execute: {

            self.imageView3.image = img3
        })
    }

    serialQueue.sync{
        let img4 = Downloader.downloadImageWithURL(imageURLs[3])
        DispatchQueue.main.async(execute: {

            self.imageView4.image = img4
        })
    }




    }
    @IBAction func sliderValueChanged(_ sender: UISlider) {

        self.sliderValueLabel.text = "\(sender.value * 100.0)"
    }

}

1 个答案:

答案 0 :(得分:1)

  

冻结用户界面

因为您正在呼叫serialQueue.sync。您几乎从不想要致电sync,在这种情况下,您肯定不会。请改用async