【发布时间】:2020-05-29 03:04:18
【问题描述】:
我正在尝试使用 Mapkit 制作地图应用程序。但是当我在模拟器上运行应用程序时,我似乎无法访问蓝点。我还是 Mapkit 的新手,任何提示都将不胜感激。这是我的代码。 ps:我正在使用 Swift 4.2 和 Xcode 11 进行编码
import UIKit
import MapKit
import CoreLocation
class mapViewController: UIViewController {
let locationManager = CLLocationManager()
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization()
checkLocationServices()
}
func setupLocationManager() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
func centerViewOnUserLocation() {
if let location = locationManager.location?.coordinate {
let region = MKCoordinateRegion.init(center: location, latitudinalMeters: 10000, longitudinalMeters: 10000)
mapView.setRegion(region, animated: true)
}
}
func checkLocationServices() {
if CLLocationManager.locationServicesEnabled() {
setupLocationManager()
checkLocationAuthorization()
} else {
}
}
func checkLocationAuthorization() {
let pin = MKPointAnnotation()
switch CLLocationManager.authorizationStatus() {
case .authorizedWhenInUse:
mapView.showsUserLocation = true
mapView.addAnnotation(pin)
break
case .denied:
break
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
break
case .restricted:
break
case .authorizedAlways:
break
}
}
}
extension mapViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// we'll be back
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
//we'll be back
}
}
【问题讨论】:
-
您是否将所需的隐私项放入 info.plist 中?
-
是的,但我仍然没有出现
-
它可以在真实设备上运行吗?是否提示您授予权限?您是否已经拒绝许可并且可能需要在隐私设置中进行更改?如果默认示例位置在其他地方,您是否还检查了整个地图(一直缩小)。除非您提供真实坐标,否则模拟器不会使用您的实际位置。
-
一个小问题:
mapView.showsUserLocation = true不在正确的位置。现在你只有在已经获得授权的情况下才打那条线。第一次运行应用程序时,不会调用该行。将其移至viewDidLoad或仅在 IB 中设置该功能。话虽如此,问题很可能会在其他地方出现(例如,一个糟糕的mapView(_:viewFor:)实现,如果有的话)。 -
无关,按照惯例,类名应以大写字母开头,例如
MapViewController.