Skip to content

Instantly share code, notes, and snippets.

@sigwyg
Created February 24, 2016 06:40
Show Gist options
  • Save sigwyg/4686876e7eac36985719 to your computer and use it in GitHub Desktop.
Save sigwyg/4686876e7eac36985719 to your computer and use it in GitHub Desktop.
SwiftでJSONを取得するサンプル
let url = NSURL(string: "http://example.com/json/")!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
if error != nil { print(error) }
else {
//print(NSString(data: data!, encoding: NSUTF8StringEncoding))
do {
// json to NSDictionary
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
// access data
if jsonResult.count > 0 {
if let items = jsonResult["Items"] as? NSArray {
for item in items {
if let title = item["title"] as? String {
let update = item["update"] as! String
}
}
} //if let items = jsonResult["Items"] as? NSArray {
} // if jsonResult.count > 0 {
} catch { print("JSON serialization Failed!") }
}
}
task.resume() // よく忘れる
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment