admin管理员组文章数量:1310074
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: ";)
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"
]
// 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() {
}
}
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/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"
]
// 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() {
}
}
Share
Improve this question
edited Feb 2 at 5:11
HangarRash
15k5 gold badges19 silver badges55 bronze badges
asked Feb 2 at 5:07
Scott CarperScott Carper
32 silver badges2 bronze badges
1 Answer
Reset to default 1When 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/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", 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
}
本文标签: swiftWhat is the easiest way to reuse the same function to call multiple API endpointsStack Overflow
版权声明:本文标题:swift - What is the easiest way to reuse the same function to call multiple API endpoints? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741855827a2401336.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论