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