Cowboy Tech

iOS项目19-Swift实现天气预报

import UIKit

class ViewController: UIViewController {

@IBOutlet var tv:UITextView?

@IBAction func btnPressed(sender:AnyObject){

    loadWeather()
}

override func viewDidLoad() {
    super.viewDidLoad()

     loadWeather()
}


func loadWeather(){

    let url = NSURL(string: "http://www.weather.com.cn/data/sk/101010100.html")

    let weatherData = NSData(contentsOfURL: url!)

    do {

let json =  try NSJSONSerialization.JSONObjectWithData(weatherData!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary

        let weatherInfo = json.objectForKey("weatherinfo")
        let city = weatherInfo!.objectForKey("city")
        let temp = weatherInfo!.objectForKey("temp")
        let wind = weatherInfo!.objectForKey("WD")
        let ws : AnyObject! = weatherInfo!.objectForKey("WS")
        tv!.text = "城市:\(city)\n温度:\(temp)\n风:\(wind)\n风级:\(ws)"
    } catch {
        print("Hello")
    }
}
}