我正在使用XCode v7.2.1,Simulator v9.2.
我有一个UIViewController,显示一个地图&应该得到我的位置&在地图上显示:
import UIKit import MapKit class LocationVC: UIViewController,MKMapViewDelegate { @IBOutlet weak var map: MKMapView! let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() map.delegate = self } override func viewDidAppear(animated: Bool) { if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse { map.showsUserLocation = true } else { locationManager.requestWhenInUseAuthorization() } } }
我在info.plist中添加了NSLocationWhenInUseUsageDescription,如下所示:
我也选择了Debug – >位置 – >自定义位置…并设置经度和芬兰赫尔辛基的纬度如下图所示:
当我运行我的应用程序时,会显示地图,但它不会获取我的位置.为什么? (我的意思是我没有在地图的任何地方看到蓝点).
===== UPDATE ====
当我的应用程序运行时,我也尝试过this,但它也没有帮助.
解决方法
您正在请求用户的位置,但实际上没有对响应做任何事情.成为位置经理的代表并回应授权变更.
此代码适用于7.2.1(在Debug – > Location中选择“Apple”之后):
import UIKit import MapKit class ViewController: UIViewController,CLLocationManagerDelegate { @IBOutlet weak var map: MKMapView! let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse { map.showsUserLocation = true } else { locationManager.requestWhenInUseAuthorization() } } func locationManager(manager: CLLocationManager,didChangeAuthorizationStatus status: CLAuthorizationStatus) { guard status == .AuthorizedWhenInUse else { print("not enabled"); return } map.showsUserLocation = true } }