Skip to content

Instantly share code, notes, and snippets.

@PetreVane
Last active February 5, 2020 13:14
Show Gist options
  • Save PetreVane/b49d71713ad93648c8dcc80ee43bc0cb to your computer and use it in GitHub Desktop.
Save PetreVane/b49d71713ad93648c8dcc80ee43bc0cb to your computer and use it in GitHub Desktop.
Upload some dummy data with URLSession.dataTask
import UIKit
// get some dummy json
let json = "{'name' : 'john snow'; 'age' : '29'}"
// get a reference to upload server
let url = URL(string: "https://httpbin.org/post")!
var request = URLRequest(url: url)
// you need to specify the http method in your request body and attach the data you need to send
request.httpMethod = "POST"
// convert your dummy json into Data
request.httpBody = json.data(using: .utf8)
// have your configuration ready
let defaultConfiguration = URLSessionConfiguration.default
defaultConfiguration.allowsCellularAccess = true
defaultConfiguration.waitsForConnectivity = true
// pass your configuration to your session
let session = URLSession(configuration: defaultConfiguration)
let task = session.dataTask(with: request) { (data, response, error) in
guard error == nil else { return }
guard let serverResponse = response as? HTTPURLResponse,
serverResponse.statusCode == 200 else { print("Unexpected status code"); return }
guard let receivedData = data else { return }
if let stringData = String(data: receivedData, encoding: .utf8) {
print("Server returned: \(stringData)")
}
}
// all tasks are initiated in 'suspended' mode; remember to start the task
task.resume()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment