网络编程之天气预报

创建网络版天气预报 在

http://api.k780.com:88

注册访问相应的接口。具体不做详述。

现在做一个前期的工作。创建一个项目,命名weatherApp,并修改info.list文件,使其支持网络下载

<key>NSAppTransportSecurity</key>  

<dict>  

 <key>NSAllowsArbitraryLoads</key><true/>  

</dict> 

在IOS最新的版本中加入了这个,应该是基于IOS的安全考虑(推测)


首位我们创建一个weather的构造类

struct Weather {

    

    var city:String?

    var weather:String?

    var temp:String?

    var iconURl:String?

    

}

系统初始化的时候进行创建weather,并赋值给weather对象。

override func viewDidLoad() {

        super.viewDidLoad()

        getWeatherData()

        

    }

 func getWeatherData(){

        let url = NSURL(string: "http://api.k780.com:88/?app=weather.today&weaid=1&&appkey=17466&sign=c2a6fd1e3ef8f80d80d8774cbb6921e1&format=json")

        let config = NSURLSessionConfiguration.defaultSessionConfiguration()

        config.timeoutIntervalForRequest = 1000

        let session = NSURLSession(configuration: config)

        session.dataTaskWithURL(url!) { (data:NSData?, res:NSURLResponse?, err:NSError?) -> Void in

            

            do{

                let jsondata = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

                let weatherDataResult = (jsondata.valueForKey("result") as? NSDictionary).map({

                    Weather(city:  $0["citynm"] as? String, weather: $0["weather"] as? String, temp: $0["temperature_curr"] as? String,iconURl:$0["weather_icon"] as? String)

                        })

                self.weatherData = weatherDataResult

             

            }catch{

               print("error")

            }

        }!.resume()

    }

利用IOS特有的侦听器 didset 对界面进行渲染

var weatherData:Weather?{

        didSet{

            configView()

        }

    }

    

    func configView(){

        cityLab.text  = self.weatherData?.city

        cityWeather.text = self.weatherData?.weather

        cityTemp.text = self.weatherData?.temp

        getImg()

        

    }

    //根据weatherData的URL,获取天气图标

    func getImg() {

       

//        let main:dispatch_queue_t = dispatch_get_main_queue()

        dispatch_async(dispatch_get_main_queue()) { () -> Void in

           

            var session2:NSURLSession!

            var dataTask2:NSURLSessionDownloadTask!

            let iconUrl = NSURL(string: (self.weatherData?.iconURl)!)

            

            //session2 = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: nil)

            session2 = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())

            //create task

            dataTask2 = session2.downloadTaskWithURL(iconUrl!, completionHandler: { (iconUrl:NSURL?, res:NSURLResponse?, err:NSError?) -> Void in

                

                let data = NSData(contentsOfURL: iconUrl!)

                let imgage = UIImage(data: data!)

                self.weatherIcon.image = imgage

                

            })

            dataTask2.resume()

            

            }

        

            }

至此,系统就能自动加载天气信息


全部代码:

//

//  ViewController.swift

//  weatherApp

//

//  Created by WHJ on 16/1/19.

//  Copyright © 2016 WHJ. All rights reserved.

//


import UIKit


struct Weather {

    

    var city:String?

    var weather:String?

    var temp:String?

    var iconURl:String?

    

}

//NSURLSessionDownloadDelegate

class ViewController: UIViewController {


    @IBOutlet weak var cityLab: UILabel!

   

    @IBOutlet weak var cityWeather: UILabel!

    

    @IBOutlet weak var cityTemp: UILabel!

    

    

    @IBOutlet weak var weatherIcon: UIImageView!


    

    var weatherData:Weather?{

        didSet{

            configView()

        }

    }

    

    func configView(){

        cityLab.text  = self.weatherData?.city

        cityWeather.text = self.weatherData?.weather

        cityTemp.text = self.weatherData?.temp

        getImg()

        

    }

    

   

    override func viewDidLoad() {

        super.viewDidLoad()

        getWeatherData()

        

    }

    func getWeatherData(){

        let url = NSURL(string: "http://api.k780.com:88/?app=weather.today&weaid=1&&appkey=17466&sign=c2a6fd1e3ef8f80d80d8774cbb6921e1&format=json")

        let config = NSURLSessionConfiguration.defaultSessionConfiguration()

        config.timeoutIntervalForRequest = 1000

        let session = NSURLSession(configuration: config)

        session.dataTaskWithURL(url!) { (data:NSData?, res:NSURLResponse?, err:NSError?) -> Void in

            

            do{

                let jsondata = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

                let weatherDataResult = (jsondata.valueForKey("result") as? NSDictionary).map({

                    Weather(city:  $0["citynm"] as? String, weather: $0["weather"] as? String, temp: $0["temperature_curr"] as? String,iconURl:$0["weather_icon"] as? String)

                        })

                self.weatherData = weatherDataResult

             

            }catch{

               print("error")

            }

        }!.resume()

    }

    

    func getImg() {

       

//        let main:dispatch_queue_t = dispatch_get_main_queue()

        dispatch_async(dispatch_get_main_queue()) { () -> Void in

            

            

            

            var session2:NSURLSession!

            var dataTask2:NSURLSessionDownloadTask!

            let iconUrl = NSURL(string: (self.weatherData?.iconURl)!)

            

            //session2 = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: nil)

            session2 = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())

            //create task

            dataTask2 = session2.downloadTaskWithURL(iconUrl!, completionHandler: { (iconUrl:NSURL?, res:NSURLResponse?, err:NSError?) -> Void in

                

                let data = NSData(contentsOfURL: iconUrl!)

                let imgage = UIImage(data: data!)

                self.weatherIcon.image = imgage

                

            })

            dataTask2.resume()

            

            }

        

            }

    /* Sent when a download task that has completed a download.  The delegate should

    * copy or move the file at the given location to a new location as it will be

    * removed when the delegate message returns. URLSession:task:didCompleteWithError: will

    * still be called.

    */

//    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL){

//        

//        let data = NSData(contentsOfURL: location)

//        let imgage = UIImage(data: data!)

//        weatherIcon.image = imgage

//    }

    


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }



}



你可能感兴趣的:(网络编程之天气预报)