5
4

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 5 years have passed since last update.

CLLocationManagerの用例

Posted at

概要

iOSアプリにおいて端末の位置情報にアクセスする場合、CoreLocationフレームワークを使用することになります。その際のCLLocationManagerの使用例になります。

CLLocationManagerの用例
import Foundation
import CoreLocation

class LocationManager: NSObject {
    var locationManager: CLLocationManager
    var latitude: String?
    var longitude: String?
    
    override init() {
        locationManager = CLLocationManager()
        super.init()
        locationManager.delegate = self
    }
    
    func startUpdating() {
        locationManager.startUpdatingLocation()
    }
    
    func requestLocation() {
        if #available(iOS 9.0, *) {
            locationManager.requestLocation()
        } else {
            locationManager.startUpdatingLocation()
        }
    }
}

extension LocationManager: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if (status == .notDetermined) {
            // Show dialog to ask user to allow getting location data
            locationManager.requestWhenInUseAuthorization()
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.first {
            self.latitude = String(describing: location.coordinate.latitude)
            self.longitude = String(describing: location.coordinate.longitude)
            
            print("Latitude:" + self.latitude! +  " Longitude:" + self.longitude! + " date:\(location.timestamp.description)")
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("# Failed to get location data.", error.localizedDescription)
    }
}

注意点

CoreLocationフレームワークを使用する場合、下記のようにInfo.plistに位置情報取得に関する説明を追記する必要があります。ここに指定した文言がダイアログとして端末に表示され、ユーザは位置情報の使用を許可するか否かを選択することができます。

  • アプリ使用時のみ位置情報を取得する場合
<key>NSLocationWhenInUseUsageDescription</key>
<string>****のため、位置情報を取得します</string>
  • 常に位置情報を取得する場合
<key>NSLocationAlwaysUsageDescription</key>
<string>****のため、常に位置情報を取得します</string>
5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?