网络编程之天气预报

创建网络版天气预报 在

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.

    }



}



转载于:https://my.oschina.net/feixuewuhen/blog/606889

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值