天氣App

恩~課程也告一個段落了,想說拿些日程生活中實用的東西來做個App,於是就誕生這個天氣App啦~App中的Data都是藉由串接第三方API得來,有興趣的可以參考以下網站。

比較特別的是若是想要取用資料需先註冊,會取得一個API Key。

網站中都有範例教你如何使用

上面的API Key呢就是將他打在網址中appid的後面,如下面範例

http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b1b15e88fa797225412429c1c50c122a1

在這個專案中沒有使用URLSession來處理和Web Service的溝通,我用了一個叫Alamofire的套件,有興趣的人可以參考以下的資料。

設定Podfile來執行套件的安裝

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'RainyShinyCloudy' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Pods for RainyShinyCloudy
pod ‘Alamofire’, ‘~> 4.0’
end

以下為取資料時的程式

func downloadForecastDate(completed: @escaping DownloadCompleter) {
//Downloading forecast weather data for TableView
let forecastURL = URL(string: FORECAST_URL)!
Alamofire.request(forecastURL).responseJSON { response in
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject> {
if let list = dict["list"] as? [Dictionary<String, AnyObject>] {
for obj in list {
let forecast = Forecast(weatherDict: obj)
self.forecasts.append(forecast)
}
self.forecasts.remove(at: 0)
self.tableView.reloadData()
}
}
completed()
}
}

GitHub 連結:

--

--