foolish::log

@takochuu のブログです。

SwiftyJSONを使ってjsonを扱う

詳解 Swift

詳解 Swift

最近Swift触っててようやくapiからデータ引っ張ってくるやり方がわかったのでメモ。 Swiftのバージョンが上がったようで、検索に引っかかるブログだと大体エラーったので。

jsonの扱いにはSwiftyJSONを使ってます。

import UIKit

class ViewController2: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        var url     = NSURL(string: "http://webservice.recruit.co.jp/relax/salon/v1?response_reserve=1&count=15&order=3&address=%E9%8A%80%E5%BA%A7&key=d80cc5011c92e61d&format=json")
        var request = NSURLRequest(URL: url!)
        NSURLConnection.sendAsynchronousRequest(request,queue: NSOperationQueue.mainQueue(), completionHandler: {
            (res: NSURLResponse!, data: NSData!, error: NSError!) in
            let json = JSON(data: data)
            
            if let image = json["results"]["salon"][0]["mood"][0]["photo"].stringValue {
                println(image)
            }
            
            if let caption = json["results"]["salon"][0]["mood"][0]["caption"].stringValue {
                println(caption)
            }
        })
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}