Multithreading 使用GCD在swift3中实现多线程
我正在开发一个基于Web服务的应用程序,由于向Web服务发送请求太快,我遇到了一次崩溃。我简直无法让GCD在Swift 3中工作,我抓狂了。我决定将其静音,然后尝试按顺序将4个web图像加载到web视图中。基于我在网上看到的一切,下面的代码应该可以工作,但它仍然冻结用户界面,直到加载所有四个图像。我做错了什么Multithreading 使用GCD在swift3中实现多线程,multithreading,swift3,Multithreading,Swift3,我正在开发一个基于Web服务的应用程序,由于向Web服务发送请求太快,我遇到了一次崩溃。我简直无法让GCD在Swift 3中工作,我抓狂了。我决定将其静音,然后尝试按顺序将4个web图像加载到web视图中。基于我在网上看到的一切,下面的代码应该可以工作,但它仍然冻结用户界面,直到加载所有四个图像。我做错了什么 import UIKit let imageURLs = ["http://www.planetware.com/photos-large/F/france-paris-eiffel-t
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)"
}
}
冻结用户界面
因为您正在调用
serialQueue.sync
。您几乎从不想调用sync
,在这种情况下,您当然不想。改用async
。就是这样!哇,我差一点就到了。在接下来的10分钟内我不会接受这个答案,但我会的。非常感谢你!