I have a very simple iOS SwiftUI app that has API calls to 7 endpoints. I've written a function to do the API call and decode the data response. In order to reuse the function I will need to replace the endpoint URL string and the class that the data gets decoded to. Passing the endpoint URL string is simple enough, but I don't know how to pass different data classes for each endpoint to the API function.
I have searched high and low for an example, but have found none for my use case. I considered using an enum, but I'm not sure how to implement that either.
Below is the code for my API call function, with the code to pass the URL string, and the data class.
func apiLoader(urlString: String) {
// Create API URL
//let url = URL(string: "https://api-hockey.p.rapidapi.com/timezone")
let url = URL(string: urlString)
guard let requestUrl = url else { fatalError() }
// Create URL Request
var request = URLRequest(url: requestUrl)
// Specify Headers to use
let headers = [
"x-rapidapi-key": "REDACTED",
"x-rapidapi-host": "REDACTED.p.rapidapi.com"
]
// Specify HTTP Method to use
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
// Send HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
// Check if Error took place
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a simple String
if let data = data.self {
do {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .formatted(dateFormatter)
let hockeyTimeZones = try decoder.decode(HockeyTimeZones.self, from: data)
hockeyTimeZones.response!.forEach { timezone in print(timezone) }
//return hockeyTimeZones
} catch {
print("Failed to load: \(error)")
//return Void()
}
}
}
task.resume()
//return HockeyTimeZones()
@Observable class HockeyTimeZones: ObservableObject, Codable {
var get : String? = nil
var parameters : [String]? = []
var errors : [String]? = []
var results : Int? = nil
var response : [String]? = []
enum CodingKeys: String, CodingKey {
case _get = "get"
case _parameters = "parameters"
case _errors = "errors"
case _results = "results"
case _response = "response"
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
get = try values.decodeIfPresent(String.self , forKey: ._get )
parameters = try values.decodeIfPresent([String].self , forKey: ._parameters )
errors = try values.decodeIfPresent([String].self , forKey: ._errors )
results = try values.decodeIfPresent(Int.self , forKey: ._results )
response = try values.decodeIfPresent([String].self , forKey: ._response )
}
init() {
}
}
When you have multiple API calls that return different types of responses that you want to decode, use Swift generics
For example:
func getData<T: Decodable>(from urlString: String) async -> T? {
guard let url = URL(string: urlString) else {
print(URLError(.badURL))
return nil // <-- todo, deal with errors
}
do {
let (data, response) = try await URLSession.shared.data(from: url)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
print(URLError(.badServerResponse))
return nil // <-- todo, deal with errors
}
return try JSONDecoder().decode(T.self, from: data) // <--- here
}
catch {
print(error)
return nil // <-- todo, deal with errors
}
}
Call it like this:
.task {
let theResponse: ApiResponse? = await getData(from: "https://...")
}
Note the important type ApiResponse?
in let theResponse: ApiResponse? = ....
,
this tells the type getData(...)
should use for decoding and to return.
Specific example code:
struct ContentView: View {
@State private var timeZones: TzResponse?
var body: some View {
List(timeZones?.response ?? [], id: \.self) { tz in
Text(tz)
}
.task {
timeZones = await getData(from: "https://api-hockey.p.rapidapi.com/timezone")
}
}
func getData<T: Decodable>(from urlString: String) async -> T? {
let apikey = "YOUR-API-KEY-HERE"
guard let url = URL(string: urlString) else {
print(URLError(.badURL))
return nil // <-- todo, deal with errors
}
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("\(apikey)", forHTTPHeaderField: "X-RapidAPI-Key")
request.addValue("api-hockey.p.rapidapi.com", forHTTPHeaderField: "X-RapidAPI-Host")
do {
let (data, response) = try await URLSession.shared.data(for: request)
//print(String(data: data, encoding: .utf8) as AnyObject)
let decodedData = try JSONDecoder().decode(T.self, from: data)
print("\n---< decodedData: \(decodedData)")
return decodedData
} catch {
print(error)
return nil // <-- todo, deal with errors
}
}
}
struct TzResponse: Codable {
let errors: [String]
let parameters: [String]
let response: [String]
let get: String
let results: Int
}