[Swift] Hit the API using Decodable / Generics

What to write in this article

-How to hit the API in Swift

Why I wrote this article

・ To check when you forget

code

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

[Swift] Hit the API using Decodable / Generics
[Parse] Hit the API using callFunctionInBackground
Hit the Docker API in Rust
Try using the Stream API in Java
Try using the Rails API (zip code)
Hit the Salesforce REST API from Java
Try using the Emotion API from Android
ChatWork4j for using the ChatWork API in Java
[Swift] About generics
[API] I tried using the zip code search API
Try using the COTOHA API parsing in Java
[Swift] API used for apps that passed the selection
[Swift] What I found by using the static property (static)
[Rails] Create an echo bot using the LINE Messaging API.
How to play MIDI files using the Java Sound API