LoginSignup
26
24

More than 5 years have passed since last update.

Swift で Dictionary 型から JSON を作成し API を呼び出す

Last updated at Posted at 2015-12-08

AWS API Gateway + Lambda で API を作成し、それを Swift から呼び出すコードを書いています。

Swift サイドで JSON を String 型で作成すると、

let str = "{\"operation\": \"create\", \"tableName\": \"sample_table\", \"Item\": {\"id\": \"\(id)\", \"name\": \"swift\"}}"

と構造が全くわからないコードになってしまいました。

Web で調べてみると Dictionary 型から JSON を作成することができるみたいでこちらのが見やすそう!
ただ、Swift 2.x のコードがパッと見つからなかったので、この方法がベストか不明ですが備忘のために残しておきます。

// 引数で緯度経度情報が渡される
// 経度緯度情報とタイムスタンプを渡すと、それをDynamoDBに格納するAPI
func postPosition(longitude: CLLocationDegrees, latitude: CLLocationDegrees) {
    let url = NSURL(string: "https://xxxxx.execute-api.ap-northeast-1.amazonaws.com/prod/position")
    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "POST"

    // ID 作成
    let now = NSDate()
    let dateFormatter = NSDateFormatter()
    dateFormatter.locale = NSLocale(localeIdentifier: "ja_JP") // ロケールの設定
    dateFormatter.dateFormat = "YYYYMMddHHmmss"
    let id = dateFormatter.stringFromDate(now)

    // JSON 化したいデータを Dictionary で作成
    let dict: [String: AnyObject] = [
        "tableName": "sample_table",
        "Item": [
            "id": "\(id)",
            "longitude": "\(longitude)",
            "latitude": "\(latitude)"
        ]
    ]

    var json: String = ""
    do {
        // Dict -> JSON
        let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: []) //(*)options??

        json = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
    } catch {
        print("Error!: \(error)")
    }

    let strData = json.dataUsingEncoding(NSUTF8StringEncoding)
    request.HTTPBody = strData

    do {
        // API POST
        let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)

        json = NSString(data: data, encoding: NSUTF8StringEncoding)! as String

        // JSON -> Dict
        let jsonDict = try NSJSONSerialization.JSONObjectWithData(data, options: []) //(*)options??
        print(jsonDict)
    } catch {
        print("error!: \(error)")
    }

}

(*) のオプションの部分が何を入れていいのかよくわからず。
Swift で JSON を作成するときのお作法知りたい。。

26
24
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
26
24