我对Swift相当新,以下代码并没有要求我提供位置权限或在MKMapView中显示我当前的位置。我已经将NSLocationAlwaysUsageDescription添加到我的info.plist,但我的模拟器仍然没有要求我的位置许可或显示我当前的loc。
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块,因为默认情况下禁用位置服务。而是检查authorizationStatus == kCLAuthorizationStatusNotDetermined的授权状态,然后请求授权。