Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift 3: GCD and URLSessionDataTask with a completionHandler
//: # Swift 3: CGD and URLSessionDataTask
import Foundation
import PlaygroundSupport
//: ### Create background queue
let queue = DispatchQueue.global(qos: .background)
//: ### Computed variable
var time:DispatchTime! {
return DispatchTime.now() + 1.0 // seconds
}
//: ### URLSession initialization
let sessionConfiguration = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfiguration)
//: ### JSON Parsing
func parseJSON(from data: Data) -> Any? {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
return json
} catch {
return nil
}
}
//: ### Call a closure on a queue
queue.async(execute: {
print(">>> [\(queue.label)]: At the queue start")
//: ### Create a URLDataTask for an URL
//: Pass a `completionHandler` to (optionally) receive the raw data, response details and error
if let url = URL(string: "http://www.sthoughts.com/dl/categories_data.json") {
let task = session.dataTask(with: url, completionHandler: {
data, response, error in
if let e = error {
print(">>>>>> [URLDataTask completion]: \(e.localizedDescription)")
return
}
if let d = data, let dataStr = String(data: d, encoding: .utf8) {
print(">>> [URLDataTask completion]: Got data, parsed result comes in a second, errors are shown immediately")
if let json = parseJSON(from: d) {
//: ### DispatchQueue delay
//: pass a `DispatchTime` object and a closure to get executed when the time arrives
DispatchQueue.main.asyncAfter(deadline: time, execute: {
print(">>> [Main Queue]: Here's the JSON")
print("\n \(dataStr)")
print(">>> [Main Queue]: Here's the parsed object\n")
debugPrint(json)
PlaygroundPage.current.finishExecution()
})
} else {
print(">>> [URLDataTask completion]: Error parsing JSON")
debugPrint(response)
print(dataStr)
PlaygroundPage.current.finishExecution()
}
} else {
//: ### Show the NSURLResponse data
//: In case the URL returns a document without a body
print(">>> \(queue.label): No data. Here's the response")
debugPrint(response)
PlaygroundPage.current.finishExecution()
}
})
//: ### Start the request
task.resume()
} else {
print(">>> [\(queue.label)]: Error: Cannot compose the URL")
PlaygroundPage.current.finishExecution()
}
print(">>> [\(queue.label)]: At the queue end. Goodbye.")
})
PlaygroundPage.current.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.