Skip to content

Instantly share code, notes, and snippets.

@chavitos
Created December 18, 2019 23:28
Show Gist options
  • Save chavitos/9cf86602ae61b29b6a2fb7eb88890f9e to your computer and use it in GitHub Desktop.
Save chavitos/9cf86602ae61b29b6a2fb7eb88890f9e to your computer and use it in GitHub Desktop.
Playground usado no vídeo DispatchGroups! Caso o arquivo não abra diretamente do xcode (apple sendo apple haha) copie o conteúdo e cole em um playground seu! :D
import UIKit
import PlaygroundSupport
/*
DispatchGroups: Monitora um grupo de tasks como uma unidade. Com isso ele consegue executar uma ação (sync ou async) após o término de todas as tasks.
*/
PlaygroundPage.current.needsIndefiniteExecution = true
//FORMA SYNC
//
//let group = DispatchGroup()
//let queue = DispatchQueue.global(qos: .userInitiated)
//
//queue.async(group: group) {
// print("Start job 1")
// Thread.sleep(until: Date().addingTimeInterval(5))
// print("End job 1")
//}
//
//queue.async(group: group) {
// print("Start job 2")
// Thread.sleep(until: Date().addingTimeInterval(1))
// print("End job 2")
//}
//
//if group.wait(timeout: .now() + 6) == .timedOut {
// print("xiiii")
//}else{
// print("deu bom!")
//}
//FORMA ASYNC
//
let group = DispatchGroup()
let queue = DispatchQueue.global(qos: .userInteractive)
let semaphore = DispatchSemaphore(value: 5)
let base = "https://wolverine.raywenderlich.com/books/con/image-from-rawpixel-id-"
let ids = [466881, 466910, 466925, 466931, 466978, 467028, 467032, 467042, 467052]
var images: [UIImage] = []
for id in ids {
guard let url = URL(string: "\(base)\(id)-jpeg.jpg") else { continue }
semaphore.wait()
group.enter()
let task = URLSession.shared.dataTask(with: url) { data,_,error in
defer {
group.leave()
semaphore.signal()
}
sleep(1)
if error == nil,
let data = data,
let image = UIImage(data: data) {
images.append(image)
}
}
task.resume()
}
group.notify(queue: queue) {
print("terminou!")
PlaygroundPage.current.finishExecution()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment