Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save TatsukiIshijima/78615d64be61238aa73518cbd417b00d to your computer and use it in GitHub Desktop.
Save TatsukiIshijima/78615d64be61238aa73518cbd417b00d to your computer and use it in GitHub Desktop.
iOS13以降の位置情報許可サンプルコード
//
// ViewController.swift
// LocationSample
//
import CoreLocation
import UIKit
class ViewController: UIViewController {
private let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
print("CLLocationManager.authorizationStatus=\(CLLocationManager.authorizationStatus().description)")
}
// Storyboard 上に適当にボタン二つ用意して紐づけて下さい
@IBAction func onRequestAlways(_ sender: Any) {
locationManager.requestAlwaysAuthorization()
}
@IBAction func onRequestWhenInUse(_ sender: Any) {
locationManager.requestWhenInUseAuthorization()
}
}
extension ViewController: CLLocationManagerDelegate {
// 位置情報の許可のステータス変更で呼ばれる
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("didChangeAuthorization status=\(status.description)")
switch status {
case .authorizedAlways:
manager.requestLocation()
break
case .authorizedWhenInUse:
manager.requestAlwaysAuthorization()
break
case .notDetermined:
break
case .restricted:
break
case .denied:
break
default:
break
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("didUpdateLocations locations=\(locations)")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("didFailWithError error=\(error.localizedDescription)")
}
}
extension CLAuthorizationStatus {
var description: String {
switch self {
case .notDetermined:
return "未選択"
case .restricted:
return "ペアレンタルコントロールなどの影響で制限中"
case .denied:
return "利用拒否"
case .authorizedAlways:
return "常に利用許可"
case .authorizedWhenInUse:
return "使用中のみ利用許可"
default:
return ""
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment