Last active
April 20, 2020 23:50
-
-
Save apple-avadhesh/600efb601d402b72601452f0d81c951e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ViewController: UIViewController { | |
var sampleImageURLs = ["https://yesofcorsa.com/wp-content/uploads/2016/12/4K-Black-Wallpaper-UHD.jpg","https://images.unsplash.com/photo-1551509134-2f9d4ec80a9b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjI0MX0&auto=format&fit=crop&w=1650&q=80","https://i.picsum.photos/id/885/200/300.jpg?grayscale"] | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
checkDispatchGroup() | |
checkDispatchSemaphor() | |
} | |
fileprivate func checkDispatchSemaphor() { | |
let semaphore = DispatchSemaphore(value: 0) | |
let dispatchQueue = DispatchQueue.global(qos: .background) | |
dispatchQueue.async { | |
self.fetchImage(self.sampleImageURLs[0]) { (_, _) in | |
print("DispatchSemaphor = Finished fetching image 1") | |
semaphore.signal() | |
} | |
semaphore.wait() | |
self.fetchImage(self.sampleImageURLs[1]) { (_, _) in | |
print("DispatchSemaphor = Finished fetching image 2") | |
semaphore.signal() | |
} | |
semaphore.wait() | |
self.fetchImage(self.sampleImageURLs[2]) { (_, _) in | |
print("DispatchSemaphor = Finished fetching image 3") | |
semaphore.signal() | |
} | |
semaphore.wait() | |
} | |
} | |
fileprivate func checkDispatchGroup() { | |
let dispatchGroup = DispatchGroup() | |
dispatchGroup.enter() | |
fetchImage(self.sampleImageURLs[0]) { (_,_) in | |
print("DispatchGroup = Finished fetching image 1") | |
dispatchGroup.leave() | |
} | |
dispatchGroup.enter() | |
fetchImage(self.sampleImageURLs[1]) { (_,_) in | |
print("DispatchGroup = Finished fetching image 2") | |
dispatchGroup.leave() | |
} | |
dispatchGroup.enter() | |
fetchImage(self.sampleImageURLs[2]) { (_,_) in | |
print("DispatchGroup = Finished fetching image 3") | |
dispatchGroup.leave() | |
} | |
dispatchGroup.notify(queue: .main) { | |
print("Finished fetching images.") | |
} | |
print("Waiting for images to finish fetching...") | |
} | |
func fetchImage(_ imageURL: String,completion: @escaping (UIImage?, Error?) -> ()) { | |
guard let url = URL(string: imageURL) | |
else { | |
return } | |
URLSession.shared.dataTask(with: url) { | |
(data, resp, err) in | |
completion(UIImage(data: data ?? Data()), nil) | |
} | |
.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment