So I have an API route that returns a JSON array of objects. For example:
[
{\"firstname\": \"Tom\", \"lastname\": \"Smith\", \"age\": 31},
{\"firstname\
Swift 5 Using Codable
Alamofire Generic Response
PersonModel.swift (create with SwiftyJsonAccelerator)
import Foundation
class PersonModel: Codable {
enum CodingKeys: String, CodingKey {
case age
case firstname
case lastname }
var age: Int? var firstname: String? var lastname: String?
init (age: Int?, firstname: String?, lastname: String?) {
self.age = age
self.firstname = firstname
self.lastname = lastname }
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
age = try container.decodeIfPresent(Int.self, forKey: .age)
firstname = try container.decodeIfPresent(String.self, forKey: .firstname)
lastname = try container.decodeIfPresent(String.self, forKey: .lastname) }
}
Generic Get Response
func genericGET(urlString: String, completion: @escaping (T?) -> ()) {
Alamofire.request(urlString)
.responseJSON { response in
// check for errors
switch response.result {
case .success(_):
do {
let obj = try JSONDecoder().decode(T.self, from: response.data!)
completion(obj)
} catch let jsonErr {
print("Failed to decode json:", jsonErr)
}
break
case .failure(_):
completion(nil)
break
}
}
}
Call this method
genericGET(urlString: "YOUR_URL") { (persons: [PersonModel]?) in
print(persons?[0].firstname)
}