0
1

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 5 years have passed since last update.

【Swift】APIを使って情報を取得するコードの詳細

0
Posted at

はじめに

この記事では、QiitaのAPIを使用した実装を例に挙げてそこで使用したメソッドの詳細を解説していきます。
⚠️当方初学のため認識違いがある可能性大です
誤りを見つけた際はコメントにて指摘していただけると幸いです🙇‍♀️🙇‍♂️

参考記事

サンプルコード

以下のコードではQiitaのAPIから情報を取得しコンソールに出力しています。

import UIKit

struct Qiita: Codable -① { 

    let title: String
    let createdAt: String
    let user: User 
    
    enum CodingKeys: String, CodingKey { -②

        case title = "title"
        case createdAt = "created_at"
        case user = "user"
    }
}

struct User: Codable {

    let name: String
    
    enum CodingKeys: String, CodingKey {
        case name = "name"
    }
}

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        getQiitaAPI()
    }
    
    func getQiitaAPI() {
        guard let url = URL(string: "https://qiita.com/api/v2/items?page=1&per_page=5")  else {  return } -③
        
        var request = URLRequest(url: url) -④
        request.httpMethod = "GET" -⑤
        
        let task = URLSession.shared.dataTask(with: url) {(data, response, err) in -⑥
            if let err = err {
                print("情報の取得に失敗しました。:", err)
                return
            }
            
            if let data = data {
                do {
                    let qiita = try JSONDecoder().decode([Qiita].self, from: data) -⑦
                    for qiita in qiita {
                        print("タイトル:\(qiita.title)\n作成日:\(qiita.createdAt)\n\(qiita.user.name)")
                    }
                    
                } catch(let err) {
                    print("情報の取得に失敗しました", err)
                }
            }
        }
        task.resume() -⑧
    }
}

目次

① Codable
② CodingKey
③ URL(string: )
④ URLRequest(url: )
⑤ .httpMethod
⑥ URLSession.shared.dataTask(with: url) { data, response, error in }
⑦ try JSONDecoder().decode()
⑧ .resume()

① Codable

Codableとは、API通信等で取得したJSONやプロパティリストを任意のデータ型に変換するプロトコル。

typealias Codable = Decodable & Encodable

DecodableとEncodableどっちもにconformしたのがCodable。

② CodingKey

CoodingKeyは、EncodeとDecodeでキー名が異なる時に一対一対応させる時に使用する。
case名をプロパティ名、rawValueをエンコード結果のフィールド名として定義する。

③ URL(string: )

String型をURL型に変換している。

④ URLRequest(url: )

URL型をURLRequest型に変換している。

⑤ .httpMethod

URLRequest型のメンバ変数。
これを"Get"とすることで情報を要求している側という指定ができる(曖昧な理解)

⑥ URLSession.shared.dataTask(with: url) { data, response, error in }

  • URLSessionとは、関連するネットワーク上のデータ転送処理群をまとめるクラス。
  • sharedとは、シングルトンのURLSessionインスタンス。
    基本的なリクエストはこれを使えばデータの取得が可能となる。

この関数では、Dataオプジェクトを経由してデータの送受信を行い、無事値が帰ってきたらdataにそのレスポンスが渡され、エラーが発生した場合errorにエラーの詳細が渡される。

⑦ try JSONDecoder().decode()

  • JSONDecoderクラスとは、JSONオブジェクトからデータ型のインスタンスをデコードするオブジェクト。
  • decode()は、第一引数に準備した型(Codableプロトコルに準拠した型)を指定し、第二引数には受け取ったJSONデータを指定する。
    第一引数の型で指定したプロパティにJSONデータをデコードする。

⑧ .resume()

処理を開始させるメソッド。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?