Skip to content

Instantly share code, notes, and snippets.

@fredlahde
Last active September 30, 2017 11:41
Show Gist options
  • Save fredlahde/ea84ed8a12805da271a6668c31e5ea4d to your computer and use it in GitHub Desktop.
Save fredlahde/ea84ed8a12805da271a6668c31e5ea4d to your computer and use it in GitHub Desktop.
HTTP in swift 3 + 4
import UIKit
import PlaygroundSupport
import Foundation
// GET Request
let url = URL(string: "https://httpbin.org/ip")
let getTask = URLSession.shared.dataTask(with: url!) { data, response, error in
guard error == nil else {
print(error!)
return
}
guard let data = data else {
print("Data is empty")
return
}
let json = try! JSONSerialization.jsonObject(with: data, options: [])
print(json)
}
getTask.resume()
// POST Request
var request = URLRequest(url: URL(string: "https://httpbin.org/post")!)
request.httpMethod = "POST"
let postString = "id=13&name=Jack"
request.httpBody = postString.data(using: .utf8)
let postTask = URLSession.shared.dataTask(with: request) {data, response, error in
guard error == nil else {
print(error!)
return
}
guard let data = data else {
print("Data is empty")
return
}
let json = try! JSONSerialization.jsonObject(with: data, options: [])
print(json)
}
postTask.resume()
PlaygroundPage.current.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment