您的位置:首页 > 理论基础 > 计算机网络

swift:使用NSJSONSerialization和SwiftyJSON两种方法解析网络返回的json格式数据

2016-03-09 15:55 1011 查看
在我的博客(下面)两个实验的基础上,使用NSJSONSerialization和SwiftyJSON两种方法解析网络返回的json格式数据,参照视频实现的"天气信息"小实验



1 创建工程



2 在百度查找需要调用的天气预报信息API



3 点击网址进去



4 复制网址http://www.weather.com.cn/data/sk/101110101.html 到浏览器地址,将返回json格式的数据如下:



5 在storyboard 文件中拖入控件 Button 和 TextView控件:



6 让控件与ViewController建立连接





7 写按钮控件的响应事件操作函数WeatherInfo()

具体如下:

func WeatherInfo(){
//访问网络

let url =NSURL(string:"http://www.weather.com.cn/adat/sk/101110101.html")
let jsonData=NSData(contentsOfURL: url!)

// //方法1
使用NSJSONSerialization解析

// do {

// let json=try NSJSONSerialization.JSONObjectWithData(jsonData!, options:[]) as! [String:AnyObject]

// let weatherInf=json["weatherinfo"] as! NSDictionary

// let city=weatherInf["city"]!

// let temp=weatherInf["temp"]!

// showWeatherInfo.text="城市:\(city)\n温度:\(temp)\n "

// }catch let error as NSError{

// print("解析出错。\(error.localizedDescription)")

// }

//方法2使用SwiftyJSON解析
let json=JSON(data:jsonData!)

let city=json["weatherinfo"]["city"]

let temp=json["weatherinfo"]["temp"]
showWeatherInfo.text="城市:\(city)\n温度:\(temp)\n"

}
9 全部代码如下:



10运行结果:点击按钮



11 最后,如果运行程序出现错误提示:

2016-03-09 15:06:27.630 Weather[3531:97547] App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary
exceptions can be configured via your app's Info.plist file.


fatal error: unexpectedly found nil while unwrapping an Optional value

原因是 Xcode7禁用了明码的HTTP请求,应该在info.plist里添加字段如下:

打开 工程主目录下info.plist

增加属性字典 App Transport Security Settings

在这个属性下增加节点 Allow Arbitrary Loads, value 为 YES

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: