迅速4地图不表示用户的当前位置

问题描述 投票:0回答:1

我试图向用户显示其在地图上的当前位置,但没有什么工作。我要去哪里错了?

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!)
    }
swift
1个回答
2
投票

分配好自己的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包含NSLocationWhenInUseUsageDescription关键 - 如记录https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html

© www.soinside.com 2019 - 2024. All rights reserved.