4
7

More than 3 years have passed since last update.

【swift5】現在地を取得した天気アプリ

Last updated at Posted at 2020-01-07

ソースはこちら

全体像

スクリーンショット 2020-01-07 17.32.25.png

①は固定。。。
これは位置情報を取得して今いる場所の地名を取得したかったができなかった。
Google Map APIの逆ジオコーディングを使用することで実現可能なので近日中に仕上げたい。

②こちらは今日の日付を取得して表示するだけなのだが、時間がなく割愛。ここもあとで実装する。 

③ここは変わる。笑
現在地の天気によって画像が変わる仕様になっている。参考のYOUTUBEの動画のかたが親切にもまとめてくださっているので使うと簡単。

④どんな天気かが表示される。

⑤現在地の気温。

アプリの詳細

このアプリは

  • Alamofire
  • SwiftyJSON
  • NVActivityIndicatorView

の3つのライブラリを使用している。

現在地から天気や気温などを取得しているのはOpenWeatherAPIである。

ソース

ソースは以下の通りです。説明が長くなってしまうのでページ下部にあるYoutubeをみていただきたい。


import UIKit
import Alamofire
import SwiftyJSON
import NVActivityIndicatorView
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {


    @IBOutlet weak var locationLabel: UILabel!
    @IBOutlet weak var dayLabel: UILabel!
    @IBOutlet weak var conditionImageView: UIImageView!
    @IBOutlet weak var conditionLabel: UILabel!
    @IBOutlet weak var temperatureLabel: UILabel!


    let apiKey = "ここはあなたのAPIkey"
    var lat = 26.8205
    var lon = 30.8024
    // loading
    var activityIndicator: NVActivityIndicatorView!
    // user location
    let locationManager = CLLocationManager()


    override func viewDidLoad() {
        super.viewDidLoad()

        let indicatorSize: CGFloat = 70
        let indicatorFrame = CGRect(x: (view.frame.width-indicatorSize)/2, y: (view.frame.height-indicatorSize)/2, width: indicatorSize, height: indicatorSize)
        activityIndicator = NVActivityIndicatorView(frame: indicatorFrame, type: .lineScale, color: UIColor.white, padding: 20.0)
        activityIndicator.backgroundColor = UIColor.black
        view.addSubview(activityIndicator)

        // use popup to check and get location
        locationManager.requestWhenInUseAuthorization()
        if (CLLocationManager.locationServicesEnabled()) {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
        }
    }


    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations[0]
        print(location)
        lat = location.coordinate.latitude
        lon = location.coordinate.longitude

        Alamofire.request("http://api.openweathermap.org/data/2.5/weather?lat=\(lat)&lon=\(lon)&appid=\(apiKey)&units=metric").responseJSON {

            response in

            self.activityIndicator.stopAnimating()
            if let responseStr = response.result.value {
                let jsonResponse = JSON(responseStr)
                let jsonWeather = jsonResponse["weather"].array![0]
                let jsonTemp = jsonResponse["main"]
                let iconName = jsonWeather["icon"].stringValue

                self.locationLabel.text = jsonResponse["name"].stringValue
                self.conditionImageView.image = UIImage(named: iconName)
                self.conditionLabel.text = jsonWeather["main"].stringValue
                self.temperatureLabel.text = "\(Int(round(jsonTemp["temp"].doubleValue)))"
            }
        }
    }
}

まとめ

今回初めてきちんとAPIから天気を取得して表示することができた。

これで自分好みの天気アプリを作りたい。

天気アプリを作った感じだが、実際には

  • APIの使い方
  • 位置情報の使い方
  • JSONの扱い方

などとその周りも扱えたのがよかった。

参考

今回はこちらの方のものを参考にさせていただきました。

4
7
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
4
7