swift在線天氣預報案例教程

經過一週準備,swift在線天氣預報視頻教程與大家見面了。這套視頻案例,需要有一定語言基礎學員。

知識點涉及很多方面。

比如:swift地理位置定位coreLocation、swift如何調用oc組件、安裝AFNetworking等還會涉及mac系統終端命令行操作。

貼圖看看界面

wKiom1QUT0bDwfrCAAKspGVdIVA930.jpgwKioL1QUUEfxfWCGAAE15ZY3luk061.jpg

實現功能簡單,但知識點用到很多,比如微信搜索地理位置等。

//  ViewController.swift
//  WeatherApp
// 文啓領航培訓
// bjflexedu.com
// qq:376610000
import UIKit
import CoreLocation
class ViewController: UIViewController,CLLocationManagerDelegate {
    
    @IBOutlet var cityName : UILabel
    
    @IBOutlet var icon : UIImageView
    
    @IBOutlet var tempTxt : UILabel
    
    @IBOutlet var busy : UIActivityIndicatorView
    
    @IBOutlet var messageInfo : UILabel
    
    let locationManage:CLLocationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
       busy.startAnimating()
        
       let img = UIImage(named: "background.jpg")
      self.view.backgroundColor = UIColor(patternImage: img)
        
        locationManage.delegate = self
      locationManage.desiredAccuracy = kCLLocationAccuracyBest
    locationManage.requestAlwaysAuthorization()
    locationManage.startUpdatingLocation()
        
        
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!){
       
       var location =  locations[locations.count-1] as CLLocation
        if location.horizontalAccuracy > 0{
           let latitude = location.coordinate.latitude
           let longitude = location.coordinate.longitude
            
            self.updateWeatherData(latitude,longitude:longitude)
            
          locationManage.stopUpdatingLocation()
            
            
        }
       
        
    }
    func updateWeatherData(latitude:CLLocationDegrees,longitude:CLLocationDegrees){
    
      let url = "http://api.openweathermap.org/data/2.5/weather"
       let params = ["lat":latitude,"lon":longitude,"cnt":0]
      let manage = AFHTTPRequestOperationManager()
        
     let success = {
        (operation:AFHTTPRequestOperation!, response:AnyObject!) -> Void in
        
        //println(response)
        
        self.busy.stopAnimating()
        self.busy.hidden = true
        self.messageInfo.text = nil
        
        
        //name
        let jsonResult:NSDictionary =  response as NSDictionary
        
        self.cityName.text = jsonResult["name"]? as String
        var tempNum:Double
        if let tempValue =   jsonResult["main"]?["temp"]? as? Double{
          tempNum = round(tempValue - 273.15)
           self.tempTxt.text = "\(tempNum) "
            
        }
        
        
        let idCon = (jsonResult["weather"]? as NSArray)[0]?["id"]? as? Int
        
        
        let nowTime = NSDate().timeIntervalSince1970
        let  sunrise = jsonResult["sys"]?["sunrise"]? as? Double
        let  sunset = jsonResult["sys"]?["sunset"]? as? Double
        var nightTime = false//true 表示黑夜;false表示白天
        if nowTime < sunrise || nowTime > sunset{
            nightTime = true
         }else{
            nightTime = false
        }
        
        self.updateIcon(idCon!,nightTime:nightTime)
        
        }
        let failure = {
            (operation:AFHTTPRequestOperation!, error:NSError!) -> Void in
            println("\(error)")
            
            self.messageInfo.text = "遠程數據取不到"
        
        }
        
        
    manage.GET(url, parameters: params, success: success, failure: failure)
        
        
        
        
    
    
    }
    
    
    func updateIcon(condition:Int,nightTime:Bool){
        
        if (condition < 300) {
            if nightTime {
                self.icon.image = UIImage(named: "tstorm1_night")
            } else {
                self.icon.image = UIImage(named: "tstorm1")
            }
        }
            // Drizzle
        else if (condition < 500) {
            self.icon.image = UIImage(named: "light_rain")
        }
            // Rain / Freezing rain / Shower rain
        else if (condition < 600) {
            self.icon.image = UIImage(named: "shower3")
        }
            // Snow
        else if (condition < 700) {
            self.icon.image = UIImage(named: "snow4")
        }
            // Fog / Mist / Haze / etc.
        else if (condition < 771) {
            if nightTime {
                self.icon.image = UIImage(named: "fog_night")
            } else {
                self.icon.image = UIImage(named: "fog")
            }
        }
            // Tornado / Squalls
        else if (condition < 800) {
            self.icon.image = UIImage(named: "tstorm3")
        }
            // Sky is clear
        else if (condition == 800) {
            if (nightTime){
                self.icon.image = UIImage(named: "sunny_night") // sunny night?
            }
            else {
                self.icon.image = UIImage(named: "sunny")
            }
        }
            // few / scattered / broken clouds
        else if (condition < 804) {
            if (nightTime){
                self.icon.image = UIImage(named: "cloudy2_night")
            }
            else{
                self.icon.image = UIImage(named: "cloudy2")
            }
        }
            // overcast clouds
        else if (condition == 804) {
            self.icon.image = UIImage(named: "overcast")
        }
            // Extreme
        else if ((condition >= 900 && condition < 903) || (condition > 904 && condition < 1000)) {
            self.icon.image = UIImage(named: "tstorm3")
        }
            // Cold
        else if (condition == 903) {
            self.icon.image = UIImage(named: "snow5")
        }
            // Hot
        else if (condition == 904) {
            self.icon.image = UIImage(named: "sunny")
        }
            // Weather condition is not available
        else {
            self.icon.image = UIImage(named: "dunno")
        }
        
        
        
        
    }
    
    
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!){
    self.messageInfo.text = "地理位置信息找不到"
        println("地理位置信息找不到\(error)")
    
    
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章