LoginSignup
3
3

More than 5 years have passed since last update.

SwiftからJSON APIを叩きたい

Posted at

NSURLSessionを利用してJSON APIを叩いてみた。ひとまず取得するだけならこんな感じ :house:

let session = NSURLSession.sharedSession()
let url = NSURL(string: "https://api.github.com/search/repositories?q=example")!
let task = session.dataTaskWithURL(url) { (data, response, error) in
// 取得したJSONから値を取り出す(SwiftyJSONを利用)
let json = JSON(data: data!)
let items = json["items"]
for (_, item) in items {
let fullName = item["full_name"]
let url = item["html_url"]
let watchers = item["watchers"]
print("*** name: (fullName), url: (url), watchers: (watchers)")
}
}
task.resume()
Playground上ではうまく動作確認できなかったので、下記コードを適当なアプリのviewDidLoadへ埋めて動作確認する。
また、生SwiftでJSONをいじるのは茨の道なので、JSONのパースにはSwiftyJSON ( https://github.com/SwiftyJSON/SwiftyJSON ) を利用してる。

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