import UIKit
class ViewController: UIViewController {
@IBOutlet var labelWeather: UITextView!
@IBAction func loadWeather(sender: AnyObject) {
testJson()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func loadWeather2(){
do{
let url = NSURL(string: "http://www.weather.com.cn/adat/sk/101100501.html")
let data = try NSData(contentsOfURL: url!,options: NSDataReadingOptions())
let json : AnyObject! = try NSJSONSerialization.JSONObjectWithData(data,options:NSJSONReadingOptions.AllowFragments)
let weatherinfo :AnyObject = json.objectForKey("weatherinfo")!
let city : AnyObject = weatherinfo.objectForKey("city")!
let wd : AnyObject = weatherinfo.objectForKey("WD")!
let ws : AnyObject = weatherinfo.objectForKey("WS")!
let temp : AnyObject = weatherinfo.objectForKey("temp")!
labelWeather.text = "城市:\(city)\n温度:\(temp)\n风向:\(wd)\n风速:\(ws)"
}catch{
print(error)
}
}
func testJson(){
do{
let url = NSURL(string: "http://www.weather.com.cn/adat/sk/101100501.html")
let user = try NSData(contentsOfURL: url!,options: NSDataReadingOptions())
let dic = user.objectFromJSONData() as! NSDictionary
let weatherinfo :AnyObject = dic.objectForKey("weatherinfo")!
let city : AnyObject = weatherinfo.objectForKey("city")!
let wd : AnyObject = weatherinfo.objectForKey("WD")!
let ws : AnyObject = weatherinfo.objectForKey("WS")!
let temp : AnyObject = weatherinfo.objectForKey("temp")!
labelWeather.text = "城市:\(city)\n温度:\(temp)\n风向:\(wd)\n风速:\(ws)"
}catch{
print(error)
}
}
}
原文链接:https://www.f2er.com/swift/325078.html