swift - Swift 4 地图未显示用户当前位置
问题描述
我试图在地图上向用户显示当前位置,但没有任何效果。我哪里错了?
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!)
}
解决方案
您showUserLocation
在分配 mapView 之前设置属性。
将来,为了避免这种错误,您可以在不使用可选的地方使用不同的编码风格,例如
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
包含 NSLocationWhenInUseUsageDescription 键 - 如记录的https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html
推荐阅读
- ios - 使用 ContactsUI 快速获取所有联系电话号码
- javascript - 用 Jest 中的测试覆盖抽象类方法
- cytoscape.js - Cytoscape.js - 将核心背景设置为深色?
- jquery - 每个模态显示相同的内容
- php - 从 xml 内容替换字符串
- ios - 如何将单元格排列成具有自定义标题的部分?
- arrays - 根据先前获得最高值的数组创建新数组
- typescript - 如何在 rollup.js 中将默认和命名的外部导入指定为 output.globals?
- swift - 如何仅使用 CNContactViewController 来创建新联系人?(迅速)
- r - “显着”和“不显着”之间的区别是否显着?