0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

デコード

Posted at

もちろん、APIからデータを取得し、JSON Decoderを使用してデータモデルに変換するコードを示します。以下はAPIリクエストとJSONデータのデコードのコードサンプルです。

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func sendRequest(_ sender: UIButton) {
        // 1. APIリクエストを送信
        if let url = URL(string: "ここにAPIのURLを入力") {
            let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
                if let error = error {
                    print("エラー:\(error)")
                    return
                }
                
                if let data = data {
                    do {
                        // 2. JSONデータをデコードしてデータモデルに変換
                        let decoder = JSONDecoder()
                        let items = try decoder.decode([Item].self, from: data)
                        
                        // 3. データモデルを使用
                        DispatchQueue.main.async {
                            // データモデルを利用してUIを更新
                            self.updateUI(with: items)
                        }
                    } catch {
                        print("JSONデータのデコードエラー:\(error)")
                    }
                }
            }
            task.resume()
        }
    }
    
    func updateUI(with items: [Item]) {
        // データモデルを使用してUIを更新する処理を行う
        print("データモデルの内容:\(items)")
    }
}

// 4. データモデルを作成
struct Item: Codable {
    let id: Int
    let name: String
    // 他のプロパティもここに追加
}

このコードのポイントは次の通りです:

  1. sendRequest メソッド内でAPIリクエストを送信します。APIのURLは適切に設定してください。

  2. APIから取得したデータをJSON Decoderを使用してデコードし、Item データモデルの配列に変換します。

  3. データモデルを使用してUIを更新するために、updateUI メソッドを非同期で呼び出します。ここで、items データモデルを利用してUIを更新できます。

  4. Item データモデルは、APIからのJSONデータの構造に対応するデータモデルです。JSON Decoderはこのデータモデルを使用してデータの変換を行います。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?