加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift2.0天气预报小实例 - 解析JSON数据(内置NSJSONSerializati

发布时间:2020-12-14 01:32:11 所属栏目:百科 来源:网络整理
导读:import UIKitclass ViewController: UIViewController { @IBOutlet var labelWeather: UITextView! @IBAction func loadWeather(sender: AnyObject) { // loadWeather2() testJson() } override func viewDidLoad() { super.viewDidLoad() // Do any additio
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)
        }
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读