微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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)
        }
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐