在 MKMapView 中以 swift 显示当前位置



我对 Swift 相当陌生,下面的代码并没有要求我提供位置权限或在 MKMapView 中显示我的当前位置。我已经将NSLocationAlwaysUsageDescription添加到我的info.plist中,但我的模拟器仍然没有要求我允许位置或显示我当前的位置。

import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController, CLLocationManagerDelegate {
  @IBOutlet var mapView: MKMapView!
  var locationManager: CLLocationManager!
  override func viewDidLoad() {
        super.viewDidLoad()
    if (CLLocationManager.locationServicesEnabled())
    {
      locationManager = CLLocationManager()
      locationManager.delegate = self
      locationManager.desiredAccuracy = kCLLocationAccuracyBest
      locationManager.requestAlwaysAuthorization()
      locationManager.startUpdatingLocation()
    }
  }
  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last
    {
      let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
      let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
      self.mapView.setRegion(region, animated: true)
    }
  }
}

提前谢谢。

启用定位服务时,您正在请求授权。if 块永远不会执行,因为默认情况下禁用位置服务。而是检查授权状态 == kCLAuthorizationStatusNotDetermined 的授权状态,然后请求授权。

最新更新