Last active
September 30, 2017 11:41
-
-
Save fredlahde/ea84ed8a12805da271a6668c31e5ea4d to your computer and use it in GitHub Desktop.
HTTP in swift 3 + 4
This file contains 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 | |
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