Swift2.0天气预报小实例 - 解析JSON数据(内置NSJSONSerialization与第三方JSONKit)

前端之家收集整理的这篇文章主要介绍了Swift2.0天气预报小实例 - 解析JSON数据(内置NSJSONSerialization与第三方JSONKit)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
import UIKit

class ViewController: UIViewController {

    @IBOutlet var labelWeather: UITextView!
    @IBAction func loadWeather(sender: AnyObject) {
// loadWeather2()
        testJson()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view,typically from a nib.
        //testJson()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func loadWeather2(){
        do{
            //通过天气预报API获取json数据
            let url = NSURL(string: "http://www.weather.com.cn/adat/sk/101100501.html")
            let data = try NSData(contentsOfURL: url!,options: NSDataReadingOptions())

            //NSData转换成NSString打印输出
// let str = NSString(data:data,encoding: NSUTF8StringEncoding)
// print(str)

            //把NSData对象转换回JSON对象
            let json : AnyObject! = try NSJSONSerialization.JSONObjectWithData(data,options:NSJSONReadingOptions.AllowFragments)
            //解析JSON数据
            let weatherinfo :AnyObject = json.objectForKey("weatherinfo")!
            let city : AnyObject  = weatherinfo.objectForKey("city")! //城市
            let wd : AnyObject = weatherinfo.objectForKey("WD")!   //风向
            let ws : AnyObject = weatherinfo.objectForKey("WS")!   //风级
            let temp : AnyObject = weatherinfo.objectForKey("temp")! //温度
            //获取
            labelWeather.text = "城市:\(city)\n温度:\(temp)\n风向:\(wd)\n风速:\(ws)"
        }catch{
            print(error)
        }
    }
    //使用第三方库 - JSONKit
    func testJson(){
        do{
            let url = NSURL(string: "http://www.weather.com.cn/adat/sk/101100501.html")
            let user = try NSData(contentsOfURL: url!,options: NSDataReadingOptions())
            //由NSData 反解析回为字典
            let dic = user.objectFromJSONData() as! NSDictionary
            let weatherinfo :AnyObject = dic.objectForKey("weatherinfo")!
            let city : AnyObject  = weatherinfo.objectForKey("city")! //城市
            let wd : AnyObject = weatherinfo.objectForKey("WD")!   //风向
            let ws : AnyObject = weatherinfo.objectForKey("WS")!   //风级
            let temp : AnyObject = weatherinfo.objectForKey("temp")! //温度
            labelWeather.text = "城市:\(city)\n温度:\(temp)\n风向:\(wd)\n风速:\(ws)"
        }catch{
            print(error)
        }
    }

}

猜你在找的Swift相关文章