URLSession
URLSession is network API provided by Apple.
Simple Usage
In this time cover simple API.
- http://localhost:8000/list (GET : return json list)
- http://localhost:8000/users/1 (GET : return one json object)
- https://localhost:8000/post (POST : any body acceptable)
This is sample codes
import UIKit import Foundation import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true class HttpClient: NSObject { func getRequest(url urlString: String) { guard let url = URL(string: urlString) else {return} let task = URLSession.shared.dataTask(with: url) {(data, response, error) in self.printData(error: error, response: response) guard let data = data else { return } print(String(data: data, encoding: .utf8)!) } task.resume() } func postRequest(url urlString: String, parameters: [String: Any]) { guard let url = URL(string: urlString) else {return} var request = URLRequest(url: url) request.httpMethod = "POST" let body = try? JSONSerialization.data(withJSONObject: parameters) request.httpBody = body let task = URLSession.shared.dataTask(with: request) { data, response, error in self.printData(error: error, response: response) guard let data = data else { return } print(String(data: data, encoding: .utf8)!) } task.resume() } func printData(error: Error?, response: URLResponse?) { if let error = error{ print(error.localizedDescription) } if let response = response as? HTTPURLResponse { print("response.statusCode = \(response.statusCode)") } } } let client = HttpClient() client.getRequest(url: "http://localhost:8000/list") client.getRequest(url: "http://localhost:8000/users/1") client.postRequest(url: "https://localhost:8000/post", parameters: ["name": "Yo", "age": "11"])
PlaygroundPage.current.needsIndefiniteExecution = true
is required to work with PlayGround
Ref
This is good example to cover basic usage : iOSでライブラリに頼らず、URLSessionを使ってHTTP通信する
コメント