Swift 4地图未显示用户当前位置
我试图在地图上显示用户的当前位置,但没有任何效果。我哪里做错了Swift 4地图未显示用户当前位置,swift,Swift,我试图在地图上显示用户的当前位置,但没有任何效果。我哪里做错了 import UIKit import CoreLocation import MapKit class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate { var window: UIWindow? var mapView: MKMapView? let locationManager =
import UIKit
import CoreLocation
import MapKit
class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
var window: UIWindow?
var mapView: MKMapView?
let locationManager = CLLocationManager()
let distanceSpan: Double = 500
override func viewDidLoad() {
super.viewDidLoad()
setupNavBar()
setupMapView()
setupLocationManager()
}
fileprivate func setupNavBar() {
self.navigationItem.title = "Near By"
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .done, target: self, action: #selector(handleDissmiss))
}
fileprivate func setupLocationManager() {self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
}
fileprivate func setupMapView() {
self.window = UIWindow(frame: UIScreen.main.bounds)
self.view.backgroundColor = UIColor.white
self.mapView?.showsUserLocation = true
self.mapView = MKMapView(frame: CGRect(x: 0, y: 20, width: (self.window?.frame.width)!, height: view.frame.height))
self.view.addSubview(self.mapView!)
}
在分配mapView之前,您正在设置
showUserLocation
属性
将来,为了避免这种错误,您可以在不使用可选代码的情况下使用不同的编码样式,例如
fileprivate func setupMapView() {
let mView = MKMapView(frame: CGRect(x: 0, y: 20, width: view.frame.width, height: view.frame.height))
mView.showsUserLocation = true
view.addSubview(mView)
self.mapView = mView
}
此外,请确保您的
Info.plist
包含NSLocationWhenUsageDescription key-如文件所述,在分配mapView之前,您正在设置showUserLocation
属性
将来,为了避免这种错误,您可以在不使用可选代码的情况下使用不同的编码样式,例如
fileprivate func setupMapView() {
let mView = MKMapView(frame: CGRect(x: 0, y: 20, width: view.frame.width, height: view.frame.height))
mView.showsUserLocation = true
view.addSubview(mView)
self.mapView = mView
}
此外,请确保您的
Info.plist
包含NSLocationWhenUsageDescription key-如文档所述完全不相关,但我建议删除所有UIWindow
和UIScreen.main.bounds
相关代码。只需引用self.view.bounds就可以了。这不仅是不必要的,而且最终会给自己带来麻烦(例如,不占用整个设备屏幕的多任务处理,等等)。完全不相关,但我建议删除所有这些UIWindow
和UIScreen.main.bounds
相关代码。只需引用self.view.bounds就可以了。这不仅是不必要的,而且最终会给自己带来麻烦(例如,多任务处理,不占用整个设备屏幕等)。