Skip to content

Instantly share code, notes, and snippets.

@PetreVane
Created December 11, 2019 12:37
Show Gist options
  • Save PetreVane/bf368b07044ce9425ebb2ecaee8bbb4d to your computer and use it in GitHub Desktop.
Save PetreVane/bf368b07044ce9425ebb2ecaee8bbb4d to your computer and use it in GitHub Desktop.
Simple URLSession Data Task with default Session Configuration
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