swift实现天气预报应用weather-forecast app Using swift

 

最近楼主在swift的自学中痛并快乐着,这个最简单的天气预报功能遇到了好多小坑, 吐血记录下代码.

/  ViewController.swift
//  Weather
//
//  Created by angela on 14/11/6.
//  Copyright (c) 2014年 angela. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
    @IBOutlet var tv:UITextView?
    
    @IBAction func btnPressed(sender:Anyobject){
        println("button clicked")
        loadWeather()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view typically from a nib.
        loadWeather()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func loadWeather(){
        var url = NSURL(string: "http://www.weather.com.cn/data/sk/101010100.html")
        println("\(url)")
        var data = NSData(contentsOfURL: url!)
        println("\(data)")
        var json : Anyobject? = NSJSONSerialization.JSONobjectWithData(data! options:NSJSONReadingOptions.AllowFragments error: nil)    
        var weatherInfo : Anyobject! = json?.objectForKey("weatherinfo") 
        var city : Anyobject! = weatherInfo?.objectForKey("city")
        var temp : Anyobject! = weatherInfo?.objectForKey("temp")
        var wind : Anyobject! = weatherInfo?.objectForKey("WD")
        var ws : Anyobject! = weatherInfo?.objectForKey("WS")
        
        tv?.text = "城市:\(city)\n温度: \(temp)\n风: \(wind)\n风级:\(ws)"
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。