我正在使用 XCode v7.2.1,Simulator v9.2。
我有一个显示 map 的 UIViewController 并且应该获取我的位置并将其显示在 map 上:
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 -> Location -> Custom Location ... 并设置芬兰赫尔辛基的经度和纬度,如下所示:
当我运行我的应用程序时,会显示 map ,但它无法获取我的位置。为什么? (我的意思是我在 map 的任何地方都没有看到蓝点)。
=====更新====
我也试过this当我的应用程序正在运行时,它也无济于事。
最佳答案
您正在请求用户的位置,但实际上并未对响应执行任何操作。成为位置管理器的委托(delegate)并响应授权更改。
这段代码适用于 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
}
}
关于ios - 我的简单 map 项目无法在模拟器中获取和显示我的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36250101/