-How to hit the API in Swift
・ To check when you forget
Sample.swift
import Foundation
// T:A structure that conforms to the Decodable protocol
internal struct Sample {
static func fetchAPI<T:Decodable>(url url:String,completion: @escaping (T) -> Void){
guard let urlComponents = URLComponents(string: url) else { return }
//Set to queryItems property if you want to filter the data using a query
//urlComponents.queryItems = [URLQueryItem(name: "name", value: "value"),]
let task = URLSession.shared.dataTask(with: urlComponents.url!){ data,response,error in
guard let jsonData = data else { return }
do {
let decodedData = try JSONDecoder().decode(T.self,from: jsonData)
completion(decodedData)
} catch {
print(error.localizedDescription)
}
}
task.resume()
}
}
HowToUse.swift
fetchAPI(url:"https://sample.com",completion:{(data) in /*Execute processing for data here*/ })
Recommended Posts