1. 程式人生 > >開發的第一個iOS app

開發的第一個iOS app

一步一步仿照著imooc的Jake Lin大神做的swift weather 寫的,雖然說不算是自己原創,收穫還是不少的。

首先Jake寫的是用AFNetworking。我是直接用Alamofire + SwiftyJson寫的

不知道是不是xcode的版本問題 匯入AFNetworking 和Alamofire總是錯誤 弄了兩天才把Alamofire匯入進去。

下面開始說說學習歷程吧

我從9月8號開始學習swift

花了兩天時間把swift的基礎看完了

跟著課程寫了一些demo 瞭解了字串 判斷 迴圈 元組 可選型等用法 有的是沒接觸過的

然後就開始寫一個有關天氣預報的app


以下是swift程式碼

//
//  ViewController.swift
//  Swift Weather
//
//  Created by chingyam on 15/9/11.
//  Copyright (c) 2015年 chingyam. All rights reserved.
//

import UIKit
import Alamofire
import CoreLocation
import SwiftyJSON

class ViewController: UIViewController , CLLocationManagerDelegate{
    let locationManager = CLLocationManager()
    
    @IBOutlet weak var loadinglabel: UILabel!
    @IBOutlet weak var loadingindicator: UIActivityIndicatorView!
    @IBOutlet weak var temperature: UILabel!
    @IBOutlet weak var icon: UIImageView!
    @IBOutlet weak var location: UILabel!
    @IBOutlet weak var Lon: UILabel!
    @IBOutlet weak var Lat: UILabel!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let background = UIImage(named:"background.png")
        //獲取背景圖片物件
        self.view.backgroundColor = UIColor(patternImage: background!)
        //設定背景圖片
        locationManager.delegate = self
        //初始化LocationManager
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        //設定LocationManger精度 設定為最好
        self.loadingindicator.startAnimating()
        //開始播放indicator動畫
        if(ios8()){
            //判斷裝置系統版本
            locationManager.requestAlwaysAuthorization()
        }
        locationManager.startUpdatingLocation()
        //開始更新地理位置資訊
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func ios8() ->Bool
    {
        var systemVersion = (UIDevice.currentDevice().systemVersion as NSString).doubleValue
        //獲取系統版本資訊
        println(systemVersion)
        return systemVersion >= 8.0
        //版本資訊>=8.0返回true 否則返回false
    }
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        var location:CLLocation = locations[locations.count-1] as! CLLocation
        //獲取最新的地理位置資訊
        if (location.horizontalAccuracy > 0) {
            //判斷是否獲取到正確的地理位置資訊
            self.locationManager.stopUpdatingLocation()
            //停止更新地理位置資訊
            println(location.coordinate.latitude)
            println(location.coordinate.longitude)
            self.Lon.text = "經度:" + String(stringInterpolationSegment:location.coordinate.longitude)
            
            self.Lat.text = "緯度:" + String(stringInterpolationSegment:location.coordinate.latitude )
            //設定label顯示經緯度
            self.updateWeatherInfo(location.coordinate.latitude,longitude:location.coordinate.longitude)
            //將經緯度以引數的形式傳入到更新天氣資訊的函式中
            
        }
    }
    
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
    {
        println(error)
        self.loadinglabel.text = "地理位置資訊不可用"
        //抓取地理位置資訊中的錯誤
    }
    func updateWeatherInfo(latitude:CLLocationDegrees , longitude:CLLocationDegrees){
        //var lat = "?lat=" + String(stringInterpolationSegment: latitude)
       // var lon = "&lon=" + String(stringInterpolationSegment: longitude)
       // var url =  "http://api.openweathermap.org/data/2.5/weather" + lat + lon + "&cnt=0"
         var url = "http://api.openweathermap.org/data/2.5/weather"
        let params = ["lat":latitude,"lon":longitude,"cnt":0]
        //呼叫天氣api的url 和引數
        Alamofire.request(.GET, url , parameters: params ).responseJSON{
            //呼叫Alamofire庫中的request方法
            (request, response,data, error) -> Void in
            if(error != nil){
                //當沒有返回值的時候返回錯誤
                println("Error:\(error)")
                println(request)
                println(response)
            }
            else{
                println("Success:\(url)")
             //   println(request)
                var json = JSON(data!)
                println(json)
                self.updateUISuccess(json)
                //當返回成功地時候,取出json傳入到更新UI的函式當中去
            }
        }
    }
    func updateUISuccess(json :JSON){
        self.loadingindicator.stopAnimating()
        self.loadingindicator.hidden = true
        //當獲取到json資料的時候,停止indicator動畫並且隱藏
        self.loadinglabel.text = nil
        //載入的標籤設定為nil
        println(json["name"].string!)
        if let tempResult = json["main"]["temp"].double
        {
            //獲取溫度資訊
            var temperature: Double
            temperature = round(tempResult - 272.15)
            //溫度資訊為開氏度 轉化為攝氏度
            self.temperature.text = "\(temperature)°C"
            self.temperature.font = UIFont.boldSystemFontOfSize(60)
            var cityName = json["name"].stringValue
            //獲取城市資訊
            self.location.font = UIFont.systemFontOfSize(40)
            self.location.text = "\(cityName)"
            
            
            var condition = json["weather"][0]["id"].intValue
            var sunset = json["sys"]["sunset"].doubleValue
            var sunrise = json["sys"]["sunrise"].doubleValue
            //獲取狀態以及日出日落的時間
            var nightTime = false
            var now = NSDate().timeIntervalSince1970
            
            if ( now > sunset || now < sunrise ){
                nightTime = true
            }
            //判斷當前時間是否晚上
            self.updateWeatherIcon(condition , nightTime:nightTime)
            //將狀態和是否晚上的資訊傳入到updateweathericon的函式當中
        }
        else{
            //如果未獲取到溫度資訊,則說明天氣資訊不正確,提示使用者天氣資訊不可用
            self.loadinglabel.text = "天氣資訊不可用"
        }
    }
    func updateWeatherIcon (condititon :Int , nightTime :Bool){
        //http://bugs.openweathermap.org/projects/api/wiki/Weather_Condition_Codes
        //根據api提供的資訊對應的天氣情況作判斷,設定天氣圖示
        if( condititon < 300 )
        {
            if nightTime {
                self.icon.image = UIImage(named: "tstorm1_night")
            }
            else{
                self.icon.image = UIImage(named: "tstorm1")
            }
        }
        else if (condititon < 500){
            self.icon.image = UIImage(named:"light_rain")
        }
        else if(condititon < 600){
            self.icon.image = UIImage(named:"shower3")
        }
        else if(condititon < 700){
            self.icon.image = UIImage(named: "snow4")
        }
        else if (condititon < 771){
            if(nightTime){
                self.icon.image = UIImage(named:"fog_night")
            }
            else{
                self.icon.image = UIImage(named:"fog")
            }
        }
        else if(condititon < 800){
            self.icon.image = UIImage(named:"tstorm3")
        }
        else if(condititon < 804){
            if(nightTime){
                self.icon.image = UIImage(named:"cloudy2_night")
            }
            else{
                self.icon.image = UIImage(named:"cloudy2")
            }
        }
        else if(condititon == 804){
            self.icon.image = UIImage(named:"overcast")
        }
        else if((condititon >= 900 && condititon < 903)||(condititon > 904 && condititon < 1000)){
            self.icon.image = UIImage(named:"tstorm3")
        }
        else if (condititon == 903){
            self.icon.image = UIImage(named:"snow5")
        }
        else if (condititon == 904){
            self.icon.image = UIImage(named:"sunny")
        }
        else{
            self.icon.image = UIImage(named:"dunno")
        }
        
    }
}