Created
December 11, 2019 12:37
-
-
Save PetreVane/bf368b07044ce9425ebb2ecaee8bbb4d to your computer and use it in GitHub Desktop.
Simple URLSession Data Task with default Session Configuration
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
import UIKit | |
import PlaygroundSupport | |
// Declare a session configuration | |
let defaultConfiguration = URLSessionConfiguration.default | |
defaultConfiguration.allowsCellularAccess = true | |
defaultConfiguration.waitsForConnectivity = true | |
// assign that configuration to a session | |
let session = URLSession(configuration: defaultConfiguration) | |
// declare an URL object, passing in a string | |
let url = URL(string: "https://jsonplaceholder.typicode.com/users") | |
// have your task | |
let task = session.dataTask(with: url!) { (data, response, error) in | |
// guard against errors | |
guard error == nil else { return } | |
guard let serverResponse = response as? HTTPURLResponse, | |
serverResponse.statusCode == 200 else { return } | |
guard let receivedData = data else { return } | |
if let stringData = String(data: receivedData, encoding: .utf8) { | |
print(stringData) | |
} | |
PlaygroundPage.current.finishExecution() | |
} | |
// remember to start your task | |
task.resume() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment