Skip to content

Instantly share code, notes, and snippets.

@dinhnhat0401
Created January 29, 2020 08:49
Show Gist options
  • Save dinhnhat0401/1832f3e8731567dbbe421e43347ef8d5 to your computer and use it in GitHub Desktop.
Save dinhnhat0401/1832f3e8731567dbbe421e43347ef8d5 to your computer and use it in GitHub Desktop.
GCD.swift
import Foundation
//let queue = DispatchQueue.global()
//let group = DispatchGroup()
//let n = 9
//for i in 0..<n {
// queue.async(group: group) {
// print("\(i): Running async task...")
// sleep(3)
// print("\(i): Async task completed")
// }
//}
//group.wait()
//print("done")
func startLoad() -> String {
var string = ""
let url = URL(string: "https://postman-echo.com/get?foo1=bar1&foo2=bar2")!
// let semaphore = DispatchSemaphore(value: 0)
let queue = DispatchQueue.global()
let group = DispatchGroup()
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print(error)
return
}
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
print(response.debugDescription)
return
}
if let mimeType = httpResponse.mimeType, mimeType == "application/json",
let data = data {
string = String(data: data, encoding: .utf8) ?? ""
// print(string)
// DispatchQueue.main.async {
// self.webView.loadHTMLString(string, baseURL: url)
// }
}
group.leave()
// semaphore.signal()
}
queue.async(group: group) {
group.enter()
task.resume()
}
// _ = semaphore.wait(timeout: DispatchTime.now().advanced(by: DispatchTimeInterval.seconds(2)))
// }
// group.wait()
// group.notify(queue: queue) {
// return "---> " + string
// }
// sleep(3)
group.wait()
return string
}
print("Loaded value = " + startLoad())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment