我正在开发一个要求用户位置权限的应用程序。我已经在我的 info.plist 文件中请求了以下所有权限
Privacy - Location Always Usage Description
Privacy - Location When In Use Usage Description
Privacy - Location Always and When In Use Usage Description
我的代码如下
import UIKit
import MapKit
import CoreLocation
class MapVC: UIViewController {
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
let authorizationStatus = CLLocationManager.authorizationStatus()
let regionRadius: Double = 1000
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
mapView.delegate = self
locationManager.delegate = self
configureLocationServices()
}
@IBAction func centerMapbtnPressed(_ sender: Any) {
if authorizationStatus == .authorizedAlways || authorizationStatus == .authorizedWhenInUse {
centerMapOnUserLocation()
}
}
}
extension MapVC: MKMapViewDelegate {
func centerMapOnUserLocation(){
guard let coordinate = locationManager.location?.coordinate else {
return
}
let coordinateRegion = MKCoordinateRegionMakeWithDistance(coordinate, regionRadius * 2, regionRadius * 2)
mapView.setRegion(coordinateRegion, animated: true)
}
}
extension MapVC: CLLocationManagerDelegate {
func configureLocationServices(){
if authorizationStatus == .notDetermined {
locationManager.requestAlwaysAuthorization()
}else {
return
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
centerMapOnUserLocation()
}
}
问题是我没有看到显示用户当前位置的蓝色标记,但它显示了用户所在的正确区域。如果我滚动到地图中的其他位置并单击其操作为 centerMapbtnPressed
的按钮,则不起作用。
尝试将showsUserLocation
设置为true
MKMapView
。似乎你还没有这样做。(有关详细信息,请参阅文档(