「CoreLocation.framework」を追加。
↓↓↓
Info.plist の
「NSLocationAlwaysAndWhenInUseUsageDescription」
と「NSLocationWhenInUseUsageDescription」 に 位置情報を使用する目的 を記載する。
この内容はユーザに位置情報の使用を許可する際に表示される。
コード
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate{
var myLocationManager:CLLocationManager?
var myLatitudeLabel:UILabel! // 緯度表示用のラベル.
var myLongitudeLabel:UILabel! // 経度表示用のラベル.
override func viewDidLoad() {
super.viewDidLoad()
// 緯度表示用のラベルを生成.
myLatitudeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 30))
myLatitudeLabel.layer.position = CGPoint(x: self.view.bounds.width/2, y:self.view.bounds.height/2+100)
// 軽度表示用のラベルを生成.
myLongitudeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 30))
myLongitudeLabel.layer.position = CGPoint(x: self.view.bounds.width/2, y:self.view.bounds.height/2+130)
myLatitudeLabel.text = ""
myLongitudeLabel.text = ""
self.view.addSubview(myLatitudeLabel)
self.view.addSubview(myLongitudeLabel)
// 現在地の取得.
myLocationManager = CLLocationManager()
myLocationManager?.delegate = self
myLocationManager?.requestWhenInUseAuthorization()
// セキュリティ認証のステータスを取得.
let status = CLLocationManager.authorizationStatus()
// まだ認証が得られていない場合は、認証ダイアログを表示.
if(status == CLAuthorizationStatus.notDetermined) {
print("didChangeAuthorizationStatus:(status)");
// まだ承認が得られていない場合は、認証ダイアログを表示.
self.myLocationManager?.requestAlwaysAuthorization()
}
// 取得精度の設定.
myLocationManager?.desiredAccuracy = kCLLocationAccuracyBest
// 取得頻度の設定.
//myLocationManager?.distanceFilter = 100 //100m移動したら位置情報更新
myLocationManager?.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// 位置情報取得に成功したときに呼び出されるデリゲート.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// 緯度・経度の表示.
myLatitudeLabel.text = "緯度:(String(describing: manager.location?.coordinate.latitude) )"
myLatitudeLabel.textAlignment = NSTextAlignment.center
myLongitudeLabel.text = "経度:(String(describing: manager.location?.coordinate.longitude))"
myLongitudeLabel.textAlignment = NSTextAlignment.center
}
// 位置情報取得に失敗した時に呼び出されるデリゲート.
func locationManager(_ manager: CLLocationManager,didFailWithError error: Error){
print("error")
}
}