1. 程式人生 > >iOS專案開發實戰(Swift)—查詢天氣小應用

iOS專案開發實戰(Swift)—查詢天氣小應用

1.新建Xcode專案,建立single view application,專案名稱為swift_Weather,選擇語言為Swift。

2.開啟Main.storyboard,新建三個控制元件,一個用於輸入城市的TextField,一個查詢按鈕Button,一個用於顯示天氣資訊的TextView。如下圖:


3.然後直接將storyboard中的三個控制元件拖到ViewController.swift中,進行繫結,繫結是否成功可以看程式碼左邊是否有一個小實的圓圈。如下圖:


4.為查詢按鈕Button新增一個Action,用於查詢對應城市的天氣。此時就需要各地天氣資訊的API介面,可以通過“http://www.weather.com.cn/data/cityinfo/城市對應的編碼.html”url得到一個JSON串,然後進行相應的解析,獲取所需要的天氣資訊。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var cityInput: UITextField!
    @IBOutlet weak var btnSearch: UIButton!
    @IBOutlet weak var result: UITextView!

    var cityDictinary = ["北京" : 101010100,"杭州" : 101210101,"常德" : 101250601,"黃岡" : 101200501]
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func btnPressed(sender: AnyObject) {
        loadWeathInfo()
    }
    
    func loadWeathInfo(){
        //注意當啟動應用程式的時候,會執行viewDidLoad
        if let cityName = cityInput.text{
            if let code = cityDictinary[cityName]{
                let str = "http://www.weather.com.cn/data/cityinfo/\(code).html"
                let url = NSURL(string: str)
                let data = NSData(contentsOfURL: url!)
                //編碼出現error:Call can throw, but it is not marked with 'try' and the error is not handled,通過加一個try解決。原因就是沒有處理錯誤
                do{
                    let json =
                    try  NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
                    let weatherInfo = json.objectForKey("weatherinfo")
                    
                    let city = weatherInfo?.objectForKey("city")
                    let maxTemp = weatherInfo?.objectForKey("temp1")
                    let minTemp = weatherInfo?.objectForKey("temp2")
                    let weather = weatherInfo?.objectForKey("weather")
                    result.text = " 城市:\(city!)\n 最高溫度:\(maxTemp!)\n 最低溫度:\(minTemp!)\n 天氣:\(weather!)\n"
                }catch{
                    print("error")
                }

            }

        }
        //沒查詢完一次就進行清空
        cityInput.text = ""
    }
}

5.程式碼新增完成之後,成功執行結果如下圖: