0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

OpenWetherMapのAPIを叩く[Swift]備忘録

Last updated at Posted at 2022-11-24

この記事参考にした
https://auto-worker.com/blog/?p=1612

OpenWeatherMapのホームページ
https://home.openweathermap.org/

https://api.openweathermap.org/data/2.5/weather?lat=34.0778755&lon=134.5615651&appid={API_KEY}&lang=ja&units=metric

レスポンス

{
"coord": {
"lon": 134.5616,
"lat": 34.0779
},
"weather": [
  {
"id": 801,
"main": "Clouds",
"description": "薄い雲",
"icon": "02d"
}
],
"base": "stations",
"main": {
"temp": 21.97,
"feels_like": 21.79,
"temp_min": 21.97,
"temp_max": 22.45,
"pressure": 1013,
"humidity": 60
},
"visibility": 10000,
"wind": {
"speed": 2.57,
"deg": 60
},
"clouds": {
"all": 20
},
"dt": 1667456496,
"sys": {
"type": 1,
"id": 8027,
"country": "JP",
"sunrise": 1667424156,
"sunset": 1667462876
},
"timezone": 32400,
"id": 1857689,
"name": "万代町",
"cod": 200
}

アイコンは
https://openweathermap.org/img/wn/02d@2x.png
"{iconCode}@2x.png"
で取得可能

緯度経度で指定したかったのでこうした
しかし、少数点以下4桁で四捨五入される様なので

lat=34.0778755&lon=134.5615651

lat=34.0779&lon=134.5616

までの指定でOK

パラメータに入れる方法がわかれば

    // OpenWeatherMapのAPIから天気情報を取得
    public func getWether() {
        let latitude = "34.0778755" // 緯度 (徳島大学の座標)
        let longitude = "134.5615651" // 経度
        let API_KEY = "xxx"
        let parameter = "lat=\(latitude)&lon=\(longitude)&appid=\(API_KEY)&lang=ja&units=metric"
        
        let urlStr = "https://api.openweathermap.org/data/2.5/weather?" + parameter
        
        state?(.busy) // 通信開始(通信中)
        apiManager.request(urlStr,
                           success: { [weak self] (response) in
            
            guard let self = self else { // HomeViewModelのself
                AKLog(level: .FATAL, message: "[self] FatalError")
                fatalError()
            }
            
            // 天気の様子が返ってくる 例: 曇
            self.weatherDiscription = response["weather"][0]["description"].string ?? "Error"
            
            // 体感気温がdoubleの形で返ってくる 例: 21.52
            if let temp = response["main"]["feels_like"].double {
                var tempStr = String(temp) // 例: "21.52"
                
                // "21.5"の時は4桁
                if tempStr.count == 5 {
                    tempStr = String(tempStr.prefix(tempStr.count-1)) // 例: "21.5"
                }
                self.weatherFeelsLike = tempStr + "℃" // 例: "21.5℃"
            }
            
            // 天気を表すアイコンコードが返ってくる 例 "02d"
            if let iconCode = response["weather"][0]["icon"].string {
                let urlStr = "https://openweathermap.org/img/wn/" + iconCode + "@2x.png"
                self.weatherIconUrlStr = urlStr
            }
            
            self.state?(.ready) // 通信完了
            
        }, failure: { [weak self] (error) in
            AKLog(level: .ERROR, message: "[API] userUpdate: failure:\(error.localizedDescription)")
            self?.state?(.error) // エラー表示
        })
    }

参考
https://qiita.com/tajihiro/items/6f1996a701ed8b0253e3
https://mo-gu-mo-gu.com/ios-alamofire/

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?