LoginSignup
2
2

More than 5 years have passed since last update.

Swift3+URLSession+JSONSerializationで JSONなREST APIを叩いて表示まで

Posted at

https://your-rest-api/items のレスポンスが以下の場合で。

サンプルJSON
{
      "Items": [
          {
              "title": "森田一義",
              "id": "big1",
          },
          {
              "title": "北野武",
              "id": "big2",
          },
          {
              "title": "明石家さんま",
              "id": "big3",
          }
      ]
  }
enum SerializationError: Error {
    case missing(String)
    case invalid(String, Any)
}

let url = URL(string: "https://your-rest-api/items")

let task = URLSession.shared.dataTask(with: url!) { data ,response ,error in

    if let data=data, let response=response{
        do{
            let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:Any]
             // すべてのitemにアクセスする
             for case let item in (json["Items"] as? [[String:Any]])!{
                    guard let title = item["title"] as? String else {
                        throw SerializationError.missing("title")
                    }
                    guard let id = item["id"] as? String else {
                        throw SerializationError.missing("id")
                    }
                    print(id + " : " + title)
                }
            } catch{
                print("Serialize Error.")
            }
        }else{
            print(error ?? " Error")
        }
    }
2
2
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
2
2