iOS项目开发实战(Swift)—查询天气小应用

1.新建Xcode项目,创建single view application,项目名称为swift_Weather,选择语言为Swift。

2.打开Main.storyboard,新建三个控件,一个用于输入城市的TextField,一个查询按钮Button,一个用于显示天气信息的TextView。如下图:

iOS项目开发实战(Swift)—查询天气小应用_第1张图片

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.代码添加完成之后,成功运行结果如下图:

iOS项目开发实战(Swift)—查询天气小应用_第2张图片

你可能感兴趣的:(iOS项目开发实战)