天气预报

Json在线解析工具: http://www.jsoneditoronline.org/

实时天气API: http://www.k780.com/api/weather.today

 

①绘制简单的UI,三个label,分别显示城市、天气、温度

②在Class外面创建Weather结构体

struct Weather {
    var city:String?
    var weather:String?
    var temp:String?
}
③编写配置天气的方法
    func configView() {
        labelCity.text = self.weatherData?.city
        labelWeather.text = self.weatherData?.weather
        labelTemp.text = self.weatherData?.temp
    }
④将上述方法放入didset内,数据变化就更新页面
    var weatherData:Weather?{
        didSet{
            configView()
        }
    }
⑤编写获取天气的方法,该方法放在viewDidLoad中
func getWeatherData(){
        //武汉天气API
        let url = NSURL(string: "http://api.k780.com:88/?app=weather.today&weaid=248&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json")
        //新建一个会话配置器
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        //配置超时时间为10秒
        config.timeoutIntervalForRequest = 10
        //建立会话
        let session = NSURLSession(configuration: config)
        //会话任务
        let task = session.dataTaskWithURL(url!,completionHandler: { (data, _, error) -> Void in
            //如果没有错误,则处理数据
            if error == nil{
                do {
                    //将json数据转化为字典
                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
                    //print(json)
                    //把json对像直接实例成自定义对象
                    let weather = (json.valueForKey("result") as? NSDictionary).map{
                        Weather(city: $0["citynm"] as? String, weather: $0["weather"] as? String, temp: $0["temperature_curr"] as? String)
                    }
                    //在主线程中更新数据
                    dispatch_async(dispatch_get_main_queue(), {
                        () ->Void in
                        self.weatherData = weather
                    })
                } catch{
                    print("json error")
                }
            }
    })
        //执行任务
        task.resume()
    }
⑥网络访问时可能会报错,参考这篇博客
http://www.cnblogs.com/luoxiaoxi/p/5046518.html
原文地址:https://www.cnblogs.com/luoxiaoxi/p/5046091.html