您的位置:首页 > 移动开发 > Swift

SwiftyJSON

2016-09-12 12:24 393 查看
首先添加SwiftyJSON第三方库 github地址

https://github.com/SwiftyJSON/SwiftyJSON

pod file文件

platform :ios, ‘8.0’

use_frameworks!

target ‘SwiftyJSON-LG’ do

pod ‘SwiftyJSON’

end

import SwiftyJSON



在storyboard中添加两个控件 一个button 一个textfield

将控件与代码进行关联

在百度中搜天气预报API接口





复制网址

@IBAction func loadWeatherinfo(sender: AnyObject) {

WeatherInfo()
}
@IBOutlet weak var showWeatherinfo: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

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"

}


效果图



github:https://github.com/DreamingLuo/SwiftyJSON-LG1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  json swift SwiftyJSON