美文网首页
Note 15 简单的天气预报

Note 15 简单的天气预报

作者: cry_0416 | 来源:发表于2016-08-10 18:59 被阅读17次

    城市信息的类

    import Foundation
    class cityInfo{
        var cityName: String?
        var areaName: String?
        var provName: String?
        var provCode: String?
        var cityCode: String?
        var areaCode: String?
        func getProvCode(arr: Array<NSDictionary>){
            for dict in arr{
                if dict["provname"] as? String == provName{
                    provCode = dict["provcode"] as? String
                }
            }
        }
        
        
        func getAreaCode(arr: Array<NSDictionary>){
            for dict in arr{
                if dict["areaname"] as? String == areaName{
                    areaCode = dict["areacode"] as? String
                }
            }
        }
        
        func getCityCode(arr: Array<NSDictionary>){
            for dict in arr{
                if dict["cityname"] as? String == cityName{
                    cityCode = dict["citycode"] as? String
                }
            }
           
        }
    }
    

    12小时天气的类

    import Foundation
    class todayDetailInfo{
        var hourTempArr: Array<hourWeatherDetail>!
        func makeDetailInfo(dict:NSDictionary){
            let typeCode:Int
            typeCode = (dict["items"]![2]["type"] as? Int)!
            if typeCode == 300{
            let arr:Array<NSDictionary> = (dict["items"]![2]["items"] as? Array<NSDictionary>)!
            hourTempArr = arr.map({
                return hourWeatherDetail(dict: $0)
            })
            }else{
                let arr:Array<NSDictionary> = (dict["items"]![1]["items"] as? Array<NSDictionary>)!
                hourTempArr = arr.map({
                    return hourWeatherDetail(dict: $0)
                })
    
            }
    
        }
        
    }
    
    class hourWeatherDetail{
        var hourTemp:String!
        var detailTime:String!
        init(dict:NSDictionary){
            hourTemp = String(dict["temp"] as! Int)
            detailTime = dict["time"] as? String
        }
    }
    

    当天天气详情

    import Foundation
    class weatherInfo{
        var todayTemp: String? //今天气温预报
        var todayClime: String? //今天天气
        var updateTime: String? //预报更新时间
        var nowTemp: String? //当前气温
        var nowDescTitle: String?//当前
        var nowDescText: String?//现在天气状况
        var API:String?//空气指数
        var APIImageUrl:NSURL?
        var bgImageUrl:NSURL?
        var APIIconBgUrl:NSURL?
        var todayDetailData:todayDetailInfo?
        
        func MakeInfo(dict: NSDictionary){
            todayTemp = dict["items"]![0]["today"]?!["temp"] as? String
            todayClime = dict["items"]![0]["today"]?!["clime"] as? String
            updateTime = dict["items"]![0]["summary"]?!["right"]!!["sysdate"] as? String
            nowTemp = dict["items"]![0]["now"]?!["temp"] as? String
            nowDescTitle = dict["items"]![0]["summary"]?!["right"]!!["date"] as? String
            nowDescText = dict["items"]![0]["now"]?!["desc"]!!["text"] as? String
            let bgImageStr = dict["items"]![0]["bg"]!!["static"]?!["clear"] as! String
            bgImageUrl = NSURL(string: bgImageStr)
            API = dict["items"]![0]["pm"]!!["text"] as? String
            let apiImageStr = dict["items"]![0]["pm"]!!["icon"]!!["logo"] as! String
            APIImageUrl = NSURL(string: apiImageStr)
            let apiImageBgStr = dict["items"]![0]["pm"]!!["icon"]!!["bgImg"] as! String
            APIIconBgUrl = NSURL(string: apiImageBgStr)
        }
        
        func makeDayDetail(dict:NSDictionary){
            todayDetailData = todayDetailInfo()
            todayDetailData!.makeDetailInfo(dict)
        }
    }
    
    

    未来几天天气的类

    import Foundation
    class futureWeather{
        var weatherForecast: Array<day>?
        func forecastInfo(dict: NSDictionary){
            weatherForecast = []
            let typeCode: Int?
             typeCode = dict["items"]![3]!["type"] as? Int
                if  typeCode == 200 {
                let forecastArr = dict["items"]![3]!["future"]?!["items"] as? Array<NSDictionary>
                for dict in forecastArr!{
                    weatherForecast!.append(day(dict: dict))
                }
                
                }else{
    
                let forecastArr = dict["items"]![2]!["future"]?!["items"] as? Array<NSDictionary>
                for dict in forecastArr!{
                    weatherForecast!.append(day(dict: dict))
                }
            }
        }
        
    }
    
    class day
    {
        var climate: String?
        var nightClimate: String?
        var dateName: String?
        var heightTemp: Int?
        var lowTemp: Int?
        init(dict: NSDictionary){
            climate = dict["climate"]!["name"] as! String?
            nightClimate = dict["nightClimate"]!["name"] as? String
            dateName = dict["dateName"] as! String?
            heightTemp = dict["temp"]!["height"] as? Int
            lowTemp = dict["temp"]!["low"] as? Int
        }
    }
    
    import UIKit
    
    class ViewController: UIViewController ,UITableViewDataSource{
    
        @IBOutlet weak var dayDetailList: UITableView!
        @IBOutlet weak var ChangCityButton: UIButton!
        @IBOutlet weak var future3Label: UILabel!
        @IBOutlet weak var future3Temp: UILabel!
        @IBOutlet weak var future3Clime: UILabel!
        @IBOutlet weak var f4Label: UILabel!
        @IBOutlet weak var f4Temp: UILabel!
        @IBOutlet weak var f4Clime: UILabel!
        @IBOutlet weak var f5Label: UILabel!
        @IBOutlet weak var f5Temp: UILabel!
        @IBOutlet weak var f5Clime: UILabel!
        @IBOutlet weak var f6Label: UILabel!
        @IBOutlet weak var f6Temp: UILabel!
        @IBOutlet weak var f6Clime: UILabel!
        @IBOutlet weak var APIIconImage: UIButton!
        @IBOutlet weak var APILabel: UILabel!
        @IBOutlet weak var bgImage: UIImageView!
        @IBOutlet weak var cityNameLabel: UILabel!
        @IBOutlet weak var todayClime: UILabel!
        @IBOutlet weak var todayTemp: UILabel!
        @IBOutlet weak var updateTime: UILabel!
        @IBOutlet weak var NOW: UILabel!
        @IBOutlet weak var weatherLabel: UILabel!
        @IBOutlet weak var nowTempLabel: UILabel!
        
        var provList:Array<NSDictionary>?
        var areaList:Array<NSDictionary>?
        var cityList:Array<NSDictionary>?
        var todayDetail:Array<NSDictionary>?
        var defaultBgImage: UIImage?
        var weather:weatherInfo!
        
        override func viewDidLoad() {
    
            super.viewDidLoad()
            defaultBgImage = UIImage(named: "weather.jpg")
            bgImage.image = defaultBgImage
            let fureWea = futureWeather()
            weather  = weatherInfo()
            let city = cityInfo()
            city.provName = "湖南"
            city.areaName = "长沙"
            city.cityName = "长沙"
            getProvList(city, weather: weather!, fureWea: fureWea)
            self.dayDetailList.hidden =  true
            self.dayDetailList.backgroundColor = UIColor.clearColor()
    
        }
        
        ////////////
        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 10
        }
        
        func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 60
        }
        
        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
            let cell  = dayDetailList.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
            cell.backgroundColor = UIColor.clearColor()
            for view in cell.subviews{
                view.removeFromSuperview()
            }
            let label1 = UILabel()
            label1.frame = CGRectMake((cell.frame.width) * 0.05, (cell.frame.height) * 0.2, (cell.frame.width) * 0.7, (cell.frame.height) * 0.6)
            let label2 = UILabel()
            label2.frame = CGRectMake((cell.frame.width) * 0.9, (cell.frame.height) * 0.2, (cell.frame.width) * 0.15, (cell.frame.height) * 0.6)
            label1.text = weather!.todayDetailData!.hourTempArr![indexPath.row].detailTime!
            label2.text = "\(weather!.todayDetailData!.hourTempArr![indexPath.row].hourTemp!)°"
            cell.addSubview(label1)
            cell.addSubview(label2)
            return cell
        }
        
        @IBAction func showDayDetail(sender: UIButton) {
            
            dayDetailList.hidden = !dayDetailList.hidden
            APILabel.hidden = !APILabel.hidden
            APIIconImage.hidden = !APIIconImage.hidden
            future3Temp.hidden = !future3Temp.hidden
            future3Clime.hidden = !future3Clime.hidden
            future3Label.hidden = !future3Label.hidden
            f4Temp.hidden = !f4Temp.hidden
            f4Clime.hidden = !f4Clime.hidden
            f4Label.hidden = !f4Label.hidden
            f5Temp.hidden = !f5Temp.hidden
            f5Clime.hidden = !f5Clime.hidden
            f5Label.hidden = !f5Label.hidden
            f6Temp.hidden = !f6Temp.hidden
            f6Clime.hidden =  !f6Clime.hidden
            f6Label.hidden = !f6Label.hidden
        }
        
        //切换城市button
        @IBAction func SelectCity(sender: UIButton) {
            
            let fureWea = futureWeather()
            let weather  = weatherInfo()
            let city = cityInfo()
            
            let secVic = selectViewController()
            secVic.bgImage = self.defaultBgImage!
            
            
            //传数据过去第二个viewController
                if self.provList != nil{
                    secVic.provList = self.provList
                } else {
                let List = [["key1":"请求省份失败","key2":"请求省份失败","errorCode":"1"],
                            ["key1":"请重新选择","key2":"重新选择","errorCode":"1"]]
                secVic.provList = List
            }
                self.presentViewController(secVic, animated: true, completion: nil)
            
            //接收省编号
            secVic.fetchData = {
                //拿到省号
                if $0 == "1"{
                    self.weatherLabel.text = "网络请求失败"
                }else{
                    
                city.provCode = String($0)
                self.getAreaList(city, weather: weather, fureWea: fureWea)
                    
                }
            }
        }
    
        
        /////省列表
        func getProvList(city:cityInfo,weather:weatherInfo,fureWea:futureWeather) {
            
            let provListPah = "http://api.class.room/?method=provs"
            self.getHttp(provListPah, closure: {
                do{
                    let provData = try NSJSONSerialization.JSONObjectWithData($0, options: .AllowFragments) as! Array<NSDictionary>
                    city.getProvCode(provData)//拿到省编号
                    self.provList = provData//获得省列表
                    if city.provName != nil{
                        self.getAreaList(city, weather: weather, fureWea: fureWea)
                    }
                }catch{
                }
            })
            
        }
        ////获得省编号,下载地区列表
        func getAreaList(city:cityInfo,weather:weatherInfo,fureWea:futureWeather){
            let areaListPath = "http://api.class.room/?method=area&provcode=" + city.provCode!
            //城市标号请求
            self.getHttp(areaListPath, closure: {
                do{
                    let areaData = try NSJSONSerialization.JSONObjectWithData($0, options: .AllowFragments) as! Array<NSDictionary>
                    city.getAreaCode(areaData)//拿到地区编号
                    self.areaList = areaData //area列表
                    
                    if city.areaName != nil{
                        self.getCityList(city, weather: weather, fureWea: fureWea)
                    }
                    
                    if city.areaCode == nil{
                        let thirdVic = selectViewController()
                        self.presentViewController(thirdVic, animated: true, completion: nil)
                        thirdVic.bgImage = self.defaultBgImage!
                        thirdVic.areaList = self.areaList
                        //拿到地区编号
                        thirdVic.fetchData = {
                            city.areaCode = String($0)
                            self.getCityList(city, weather: weather, fureWea: fureWea)
                        }
                    }
                }catch{
                }
            })
        }
        ///获得地区编码下载城市列表
        func getCityList(city:cityInfo,weather:weatherInfo,fureWea:futureWeather){
            let cityListPath = "http://api.class.room/?method=city&areacode=" + city.areaCode!
    
            self.getHttp(cityListPath, closure: {
                do{
                    let cityData = try NSJSONSerialization.JSONObjectWithData($0, options: .AllowFragments) as! Array<NSDictionary>
                    city.getCityCode(cityData)
                    self.cityList = cityData
                    if city.cityName != nil{
                        self.getWeatherDetail(city, weather: weather, fureWea: fureWea)
                    }
                    if city.cityCode == nil{
                        let fourthVic = selectViewController()
                        self.presentViewController(fourthVic, animated: true, completion: nil)
                        fourthVic.bgImage = self.defaultBgImage!
                        fourthVic.cityList = self.cityList!
                        //拿到城市编号和城市名
                        fourthVic.fetchCityData = {
                            city.cityCode = $0
                            city.cityName = $1
                            self.getWeatherDetail(city, weather: weather, fureWea: fureWea)
                        }
                    }
                }catch{
                }
            })
            
        }
        ////获得城市编码后下载天气数据
        func getWeatherDetail(city:cityInfo,weather:weatherInfo,fureWea:futureWeather){
            let cityWeatherPath =  "http://tq.91.com/api/?city=" + city.cityCode! + "&act=210&nt=10&pid=168&mt=1"
            dispatch_async(dispatch_get_main_queue()) {
            self.getHttp(cityWeatherPath, closure: {
                do{
                    let weatherData = try NSJSONSerialization.JSONObjectWithData($0, options: .AllowFragments) as! NSDictionary
                    weather.MakeInfo(weatherData)
                    weather.makeDayDetail(weatherData)
                    fureWea.forecastInfo(weatherData)
                    dispatch_async(dispatch_get_main_queue(), {
                        self.downImage(weather.bgImageUrl!)
                        self.downIconImage(weather.APIImageUrl!)
                        self.downIconBgImage(weather.APIIconBgUrl!)
                        self.updateDataAtView(city, weather: weather,fureWea: fureWea)
                        self.dayDetailList.dataSource = self
                        self.dayDetailList.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
                        self.dayDetailList.reloadData()
                    })
                }catch{
                }
            })
            }
        }
    ///////网络请求
        func getHttp(path: String,closure: (data:NSData)->Void){
            let url = NSURL(string: path)
            let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in
                if error == nil{
                    if let httpResponse = response as? NSHTTPURLResponse{
                        if httpResponse.statusCode == 200{
                            if let d = data{
                                closure(data:d)
                            }
                        } else {
                            print(httpResponse.statusCode)
                        }
                    } else {
                        print(response)
                    }
                } else {
                    print(error)
                }
            }
            task.resume()
        }///////
        ////请求图片数据
        func getImage(url:NSURL, closure: (data:NSData)->Void){
            let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
                if error == nil {
                    if let httpResponse = response as? NSHTTPURLResponse {
                        if httpResponse.statusCode == 200 {
                            if let d = data {
                                    closure(data:d)
                            }
                        } else {
                            print(httpResponse.statusCode)
                        }
                    } else {
                        print(response)
                    }
                } else {
                    print(error)
                }
            }
            task.resume()
        }
        ///显示数据
        func updateDataAtView(city: cityInfo, weather: weatherInfo,fureWea:futureWeather){
            
            cityNameLabel.text = "\(city.cityName!)"
            weatherLabel.text = "\(weather.nowDescText!)"
            nowTempLabel.text = "  " + weather.nowTemp! + "°"
            NOW.text = weather.nowDescTitle
            updateTime.text = "更新时间:\(weather.updateTime!)"
            todayTemp.text = "\(weather.todayTemp!)  "
            todayClime.text = weather.todayClime
            APILabel.text = weather.API
            
            future3Label.text = "\(fureWea.weatherForecast![2].dateName!)"
            future3Temp.text = "\(fureWea.weatherForecast![2].heightTemp!)/\(fureWea.weatherForecast![2].lowTemp!)℃  "
            future3Clime.text = "\(fureWea.weatherForecast![2].climate!)/\(fureWea.weatherForecast![2].nightClimate!)"
            
            f4Label.text = "\(fureWea.weatherForecast![3].dateName!)"
            f4Temp.text = "\(fureWea.weatherForecast![3].heightTemp!)/\(fureWea.weatherForecast![3].lowTemp!)℃  "
            f4Clime.text = "\(fureWea.weatherForecast![3].climate!)/\(fureWea.weatherForecast![3].nightClimate!)"
            
            f5Label.text = "\(fureWea.weatherForecast![4].dateName!)"
            f5Temp.text = "\(fureWea.weatherForecast![4].heightTemp!)/\(fureWea.weatherForecast![4].lowTemp!)℃  "
            f5Clime.text = "\(fureWea.weatherForecast![4].climate!)/\(fureWea.weatherForecast![4].nightClimate!)"
            
            f6Label.text = "\(fureWea.weatherForecast![5].dateName!)"
            f6Temp.text = "\(fureWea.weatherForecast![5].heightTemp!)/\(fureWea.weatherForecast![5].lowTemp!)℃  "
            f6Clime.text = "\(fureWea.weatherForecast![5].climate!)/\(fureWea.weatherForecast![5].nightClimate!)"
    
        }//////
        //下载背景图
        func downImage(url:NSURL){
            getImage(url) { (data) in
                dispatch_async(dispatch_get_main_queue(), {
                    self.defaultBgImage = UIImage(data: data)
                    self.bgImage.image = self.defaultBgImage
                })
            }
        }
        ///下载空气质量图片
        func downIconImage(url:NSURL){
            getImage(url) { (data) in
                dispatch_async(dispatch_get_main_queue(), { 
                    let IconImage = UIImage(data: data)
                    self.APIIconImage.setImage(IconImage, forState: .Normal)
                })
            }
        }
        ///下载空气质量图标背景图
        func downIconBgImage(url:NSURL){
            getImage(url) { (data) in
                dispatch_async(dispatch_get_main_queue(), {
                    let image = UIImage(data: data)
                    self.APIIconImage.setBackgroundImage(image, forState: .Normal)
                })
            }
        }
    
    }
    

    代码里面的API

    相关文章

      网友评论

          本文标题:Note 15 简单的天气预报

          本文链接:https://www.haomeiwen.com/subject/szejsttx.html