47
43

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] AlamofireでApiを叩いて、SwiftyJSONでレスポンスデータを展開する

Last updated at Posted at 2015-07-08

はじめに

RailsでJSON Apiを作成したので、そこと通信をするiOSアプリをSwiftで作ることになりました。
以前はHTTP通信部分にNSURLSessionやAFNetworkを使っていましたが、今回はSwiftで書かれたAlamofireを使って見ることにしました。
JSONのSerializeにはNSJSONSerializationを使っていたところを、SwiftyJSONを使ってみることにしました。

やったこと

とりあえずテストとしてAppDelegate.swiftあたりに書いてみました。

import UIKit
import Alamofire
import SwiftyJSON
    ・
    ・
    ・
        Alamofire.request(.GET, "http://foo.com/api/v1/bar/1", parameters: ["foo": "bar"])
        .response { (request, response, data, error) in
            println(request)
            println(response)
        }
        .responseJSON { (_, _, json_data, _) in
            println(json_data)
            let json = JSON(json_data!)
            println(json)
            println(json["bar"])
            println(json["bar"]["hoge_id"])
        }
    }
}
request
<NSMutableURLRequest: 0x7fab3b28b720> { URL: http://foo.com/api/v1/bar/1?foo=bar }
response
Optional(<NSHTTPURLResponse: 0x7fab38d60bc0> { URL: http://foo.com/api/v1/bar/1?foo=bar } { status code: 200, headers {
   ・
   ・
    "Cache-Control" = "max-age=0, private, must-revalidate";
    Connection = "keep-alive";
    "Content-Type" = "application/json; charset=utf-8";
   ・
   ・
   ・
} })
json_data
Optional({
    bar =     {
        "created_at" = "2015-07-01T12:25:41.438+09:00";
        id = 1;
        "updated_at" = "2015-07-01T12:25:41.438+09:00";
        "hoge_id = 1"
    };
})
json
{
  "bar" : {
    "id" : 1,
    "created_at" : "2015-07-01T12:25:41.438+09:00",
    "updated_at" : "2015-07-01T12:25:41.438+09:00",
    "hoge_id" : 1
  }
}
json["bar"]
  "id" : 1,
  "created_at" : "2015-07-01T12:25:41.438+09:00",
  "updated_at" : "2015-07-01T12:25:41.438+09:00",
  "hoge_id" : 1
json["bar"]["hoge_id"]
1

まとめ

今回はとても単純な例ですが、今までよりもとても直感的に使えそうです。
複雑な操作は今後。

References

47
43
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
47
43

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?