在我的部落格(下面)兩個實驗的基礎上,使用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