Advertisement
thieumao

Parse Json with Swift in iOS Programming

May 12th, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.39 KB | None | 0 0
  1. import UIKit
  2.  
  3. class ViewController: UIViewController {
  4.  
  5.     override func viewDidLoad() {
  6.         super.viewDidLoad()
  7.        
  8.         // load file json
  9.         let urlString = "http://www.learnswiftonline.com/Samples/subway.json"
  10.         let url : NSURL = NSURL(string: urlString)!
  11.         let urlSession = NSURLSession.sharedSession()
  12.        
  13.         // query url
  14.         let jsonQuery = urlSession.dataTaskWithURL(url) { (data, reponse, error) in
  15.             if (error != nil){
  16.                 print("\(error!.localizedDescription)");
  17.             }
  18.             var err : NSError?
  19.             var jsonResult = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
  20.            
  21.             if (err != nil) {
  22.                 print("error : \(err?.localizedDescription)")
  23.             }
  24.            
  25.             let jsonData : NSArray! = jsonResult["stations"] as! NSArray
  26.             if jsonData != nil {
  27.                 print("\(jsonData)");
  28.             }
  29.            
  30.             for var element in jsonData {
  31.                 print((element["stationName"]))
  32.                 print((element["buildYear"]))
  33.             }
  34.         }
  35.         jsonQuery.resume()
  36.     }
  37.  
  38.     override func didReceiveMemoryWarning() {
  39.         super.didReceiveMemoryWarning()
  40.         // Dispose of any resources that can be recreated.
  41.     }
  42.  
  43.  
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement