Last active
February 5, 2020 13:14
-
-
Save PetreVane/b49d71713ad93648c8dcc80ee43bc0cb to your computer and use it in GitHub Desktop.
Upload some dummy data with URLSession.dataTask
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 | |
// 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