LoginSignup
8
6

More than 5 years have passed since last update.

OpenWeatherMapApiを用いて天気情報の取得(Swift3.0)

Last updated at Posted at 2017-01-19

OpenWeatherMapAPiを叩いてみた

OpenWeatherMapApiは緯度、経度や都市の名前を指定するとその地点の天気情報を提供している。使い方に関しては公式ホームページに詳しく載っているので省略する。(初心者向け)
ソースコード

test.swift
private let OpenWeatherMapUrl = "http://api.openweathermap.org/data/2.5/weather?q=(都市名)&appid=(ApiKey)"

func openweathermap(){
    // openweathermapApiを用いて各情報を取得
    let url = NSURL(string: self.OpenWeatherMapUrl)!
    let task = URLSession.shared.dataTask(with: url as URL, completionHandler: {data, response, error in
        // リソースの取得が終わると、ここに書いた処理が実行
        let json = JSON(data: data!)
        print(json)
    })
    task.resume()
}

//出力結果
{
  "main" : {
    "humidity" : 55,
    "temp_max" : 290.15,
    "temp_min" : 286.15,
    "temp" : 288.01,
    "pressure" : 1019
  },
  "name" : "都市名",
  "id" : id名,
  "coord" : {
    "lon" : 緯度,
    "lat" : 経度
  },
  "weather" : [
    {
      "id" : 803,
      "main" : "Clouds",
      "icon" : "04n",
      "description" : "broken clouds"
    }
  ],
  "clouds" : {
    "all" : 75
  },
  "dt" : 1484400600,
  "base" : "stations",
  "sys" : {
    "id" : 7623,
    "message" : 0.0101,
    "country" : "JP",
    "type" : 1,
    "sunset" : 1484384300,
    "sunrise" : 1484345892
  },
  "cod" : 200,
  "visibility" : 10000,
  "wind" : {
    "speed" : 6.7,
    "deg" : 30
  }
}

今回はURLSessionを用いて通信を行った。
また、取得したデータは扱いやすいようにSwiftyJsonを用いてJson型にした。個々のデータを取得する際には以下のように記述すれば良い。

print(json["main"]["pressure"])
print(json["weather"][0]["main"])

追記
let json = JSON(data: data!)
上記は取得したデータをJson型に変換する一文です。この際に取得したデータを非オプショナル型で宣言しなさい!と言われます。ですが、通信に失敗してデータが取得出来なかった場合などは、このような記述にするとUnwrapped出来ません!とerrorになってしまいます。そのため、実際に実装する際にはdataが取得できたかどうか確認してからJson型に変換するか、通信を行った際に取得できるerror情報などを利用して実装すればよいのかなぁ。

8
6
2

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
8
6