標籤:
學習來自《小波說雨燕 第二季 網路編程(入門篇)》
工具:xcode6.4
首先在Main.storyborad中添加並設定好三個label做簡單的介面顯示:
1 import UIKit 2 3 //1、construct a constructs 4 struct Weather { 5 var city: String? 6 var weather: String? 7 var temp: String? 8 }//為什麼不實用class呢,因為結構體初始化方便,不用寫初始化方法 9 10 11 12 class ViewController: UIViewController {13 14 @IBOutlet weak var labelCity: UILabel!15 @IBOutlet weak var labelWeather: UILabel!16 @IBOutlet weak var labelTemp: UILabel!17 18 //3、接下來需要加一個計算屬性19 var weatherData:Weather?{20 //4、發生變化的話,用swift專屬的文法21 didSet {22 configView()23 }24 }25 26 //2、然後考慮到:一啟動app就是要重新整理資料,所以需要這麼一個方法27 func configView(){28 labelCity.text = self.weatherData?.city29 labelWeather.text = self.weatherData?.weather30 labelTemp.text = self.weatherData?.temp31 }32 33 //4、建立一個擷取天氣資料的方法34 func getWeatherData()35 {36 //NSURLSession37 //<1>資源定位 NSURL 載入的網址38 let url = NSURL(string: "http://api.k780.com:88/?app=weather.today&weaid=238&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json")39 println(url!)40 //<2>URL Session Configuration(URL會話配置):磁碟緩衝、記憶體緩衝、系統後台執行。下面用預設的磁碟緩衝41 let config = NSURLSessionConfiguration.defaultSessionConfiguration()42 println(config)43 config.timeoutIntervalForRequest = 10//配置逾時時間,即使用者載入網路的時間10秒以內44 //<3>建立會話45 let session = NSURLSession(configuration: config)46 47 //<4>會話的任務48 let task = session.dataTaskWithURL(url!, completionHandler: { (data,_, error) -> Void in49 //<6>如果串連沒有錯誤,則處理資料50 if error == nil {51 if let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil)as?NSDictionary{52 //下面擷取資料轉為字典,然後把json對象,直接執行個體化成自訂的對象,這步相對複雜,因為用到一個map函數53 let weather:Weather = (json.valueForKey("result") as? NSDictionary).map{54 Weather(55 city: $0["citynm"] as? String56 ,weather: $0["weather"] as? String57 ,temp: $0["temperature_curr"] as? String58 )59 }!60 //<8>更新介面卻很慢,是因為更新介面不在主線程中,所以要在主線程中跟新這個介面61 dispatch_async(dispatch_get_main_queue(), {62 ()->Void in63 //<7>擷取資料之後,就要在視圖中顯示64 self.weatherData = weather65 })66 67 68 }69 }70 })//第二個參數就是task完成之後要做的操作71 //<5>執行任務72 task.resume()73 74 75 }76 override func viewDidLoad() {77 super.viewDidLoad()78 getWeatherData()79 }80 81 override func didReceiveMemoryWarning() {82 super.didReceiveMemoryWarning()83 }84 85 86 }
然後運行就可以了:
swift網路編程入門應用:天氣預報