Swift2.0天气预报小实例 - 解析JSON数据(内置NSJSONSerialization与第三方JSONKit)

前端之家收集整理的这篇文章主要介绍了Swift2.0天气预报小实例 - 解析JSON数据(内置NSJSONSerialization与第三方JSONKit)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. import UIKit
  2.  
  3. class ViewController: UIViewController {
  4.  
  5. @IBOutlet var labelWeather: UITextView!
  6. @IBAction func loadWeather(sender: AnyObject) {
  7. // loadWeather2()
  8. testJson()
  9. }
  10.  
  11. override func viewDidLoad() {
  12. super.viewDidLoad()
  13. // Do any additional setup after loading the view,typically from a nib.
  14. //testJson()
  15. }
  16.  
  17. override func didReceiveMemoryWarning() {
  18. super.didReceiveMemoryWarning()
  19. // Dispose of any resources that can be recreated.
  20. }
  21.  
  22. func loadWeather2(){
  23. do{
  24. //通过天气预报API获取json数据
  25. let url = NSURL(string: "http://www.weather.com.cn/adat/sk/101100501.html")
  26. let data = try NSData(contentsOfURL: url!,options: NSDataReadingOptions())
  27.  
  28. //NSData转换成NSString打印输出
  29. // let str = NSString(data:data,encoding: NSUTF8StringEncoding)
  30. // print(str)
  31.  
  32. //把NSData对象转换回JSON对象
  33. let json : AnyObject! = try NSJSONSerialization.JSONObjectWithData(data,options:NSJSONReadingOptions.AllowFragments)
  34. //解析JSON数据
  35. let weatherinfo :AnyObject = json.objectForKey("weatherinfo")!
  36. let city : AnyObject = weatherinfo.objectForKey("city")! //城市
  37. let wd : AnyObject = weatherinfo.objectForKey("WD")! //风向
  38. let ws : AnyObject = weatherinfo.objectForKey("WS")! //风级
  39. let temp : AnyObject = weatherinfo.objectForKey("temp")! //温度
  40. //获取
  41. labelWeather.text = "城市:\(city)\n温度:\(temp)\n风向:\(wd)\n风速:\(ws)"
  42. }catch{
  43. print(error)
  44. }
  45. }
  46. //使用第三方库 - JSONKit
  47. func testJson(){
  48. do{
  49. let url = NSURL(string: "http://www.weather.com.cn/adat/sk/101100501.html")
  50. let user = try NSData(contentsOfURL: url!,options: NSDataReadingOptions())
  51. //由NSData 反解析回为字典
  52. let dic = user.objectFromJSONData() as! NSDictionary
  53. let weatherinfo :AnyObject = dic.objectForKey("weatherinfo")!
  54. let city : AnyObject = weatherinfo.objectForKey("city")! //城市
  55. let wd : AnyObject = weatherinfo.objectForKey("WD")! //风向
  56. let ws : AnyObject = weatherinfo.objectForKey("WS")! //风级
  57. let temp : AnyObject = weatherinfo.objectForKey("temp")! //温度
  58. labelWeather.text = "城市:\(city)\n温度:\(temp)\n风向:\(wd)\n风速:\(ws)"
  59. }catch{
  60. print(error)
  61. }
  62. }
  63.  
  64. }

猜你在找的Swift相关文章