はじめに
Alamofireにデコードした結果を返してくれる便利なメソッドがあったので紹介します
サンプルデータ
import Foundation
struct SampleModel: Codable {
let id: Int
let idStr, name, screenName, location, description: String
enum CodingKeys: String, CodingKey {
case id
case idStr = "id_str"
case name
case screenName = "screen_name"
case location
case description
}
}
実装
AF.request("https://sample.com/", method: .get, headers: headers).responseDecodable(of: SampleModel.self) { response in
switch response.result {
case .success(let data):
print(data)
case .failure(let error):
print(error)
}
}
おわり
いつもはresponseData
を使ってましたが絶対デコードするならresponseDecodable
こっちの方が楽ですね