2015/02/12

Swift IOS Read JSON from url

JSON資料使用高雄市公車路線資料

先將url透過NSURL建構子建立該常數,再將NSURL給予NSData建構子,回傳資料為NSData

let data = getDataFromUrl(url)!

func getDataFromUrl(url:String) -> NSData? {
        let url = NSURL(string: url)
        
        if(url == ""){
            return nil
        }
        
        return NSData(contentsOfURL: url!)
    }



再透過NSJSONSerialization.JSONObjectWithData方法將Data轉成AnyObject

並將其JSON依照高雄市公車路線資料的格式輸出




func printJson(object:AnyObject){
        if let array = object as? NSArray{
            for temp in array{
                var id:AnyObject! = temp["ID"]
                var departure:AnyObject! = temp["departureZh"]
                var destination:AnyObject! = temp["destinationZh"]
                println("車牌號碼\(id) 起點\(departure) 目的\(destination)")
            }
        }
    }




Code:
//
//  ViewController.swift
//  ReadJSON
//
//  Created by C.Y.Fang on 2/12/15.
//  Copyright (c) 2015 C.Y.Fang. All rights reserved.
//

import UIKit

class ViewController: UIViewController {


    let url = "http://data.kaohsiung.gov.tw/Opendata/DownLoad.aspx?Type=2&CaseNo1=AP&CaseNo2=9&FileType=1&Lang=C&FolderType="
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let data = getDataFromUrl(url)!
        let json:AnyObject? = NSJSONSerialization.JSONObjectWithData(data,
            options: NSJSONReadingOptions.AllowFragments, error: nil)
        printJson(json!)
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func getDataFromUrl(url:String) -> NSData? {
        let url = NSURL(string: url)
        
        if(url == ""){
            return nil
        }
        
        return NSData(contentsOfURL: url!)
    }
    
    func printJson(object:AnyObject){
        if let array = object as? NSArray{
            for temp in array{
                var id:AnyObject! = temp["ID"]
                var departure:AnyObject! = temp["departureZh"]
                var destination:AnyObject! = temp["destinationZh"]
                println("車牌號碼\(id) 起點\(departure) 目的\(destination)")
            }
        }
    }

}

執行結果: