概要
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>