0
1

More than 1 year has passed since last update.

【Swift】Alamofireで簡単にデコードする方法

Posted at

はじめに

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こっちの方が楽ですね

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1