import UIKitclass 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) } }}总结
以上是内存溢出为你收集整理的Swift2.0天气预报小实例 - 解析JSON数据(内置NSJSONSerialization与第三方JSONKit)全部内容,希望文章能够帮你解决Swift2.0天气预报小实例 - 解析JSON数据(内置NSJSONSerialization与第三方JSONKit)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)