我目前正在开发一款iOS应用程序,其中一项功能包括定位夜生活场所。但是,当我的MapView加载时,即使已授予位置访问权限,也不会显示当前用户位置。
这是我的代码:
import UIKit
import MapKit
import CoreLocation
class BarMapVC: UIViewController {
@IBOutlet weak var searchBtn: UIBarButtonItem!
@IBOutlet weak var doneBtn: UIBarButtonItem!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var locationBtn: UIButton!
@IBOutlet weak var barMapView: MKMapView!
var locationManager = CLLocationManager()
let authorizationStatus = CLLocationManager.authorizationStatus()
let regionRadius: Double = 1000
override func viewDidLoad() {
super.viewDidLoad()
searchBar.isHidden = true
barMapView.delegate = self
locationManager.delegate = self
configureLocationServices()
centerMapOnUserLocation()
}
@IBAction func searchBtnWasPressed(_ sender: Any) {
searchBar.isHidden = false
}
@IBAction func doneBtnWasPressed(_ sender: Any) {
dismiss(animated: true)
}
@IBAction func locationBtnWasPressed(_ sender: Any) {
if authorizationStatus == .authorizedAlways || authorizationStatus == .authorizedWhenInUse {
centerMapOnUserLocation()
}
}
}
extension BarMapVC: MKMapViewDelegate {
func centerMapOnUserLocation() {
guard let coordinate = locationManager.location?.coordinate else { return }
let coordinateRegion = MKCoordinateRegionMakeWithDistance(coordinate, regionRadius * 2.0, regionRadius * 2.0)
barMapView.setRegion(coordinateRegion, animated: true)
}
}
extension BarMapVC: CLLocationManagerDelegate {
func configureLocationServices() {
if authorizationStatus == .notDetermined {
locationManager.requestAlwaysAuthorization()
} else {
return
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
centerMapOnUserLocation()
}
}
我正在使用CLLocation Manager,符合mapViewDelegate,以及所有需要的插座。我做错了什么?
答案 0 :(得分:0)
您可以在地图视图中进行设置:
barMapView.showsUserLocation = true