不使用 CLLocationManager 显示当前位置

Display current location without using CLLocationManager

我是 iOS 的新手,我对查找当前用户位置有疑问。我正在阅读 Apple 文档:

Displaying the User’s Current Location on the Map Map Kit includes built-in support for displaying the user’s current location on the map. To show this location, set the showsUserLocation property of your map view object to YES. Doing so causes the map view to use Core Location to find the user’s location and add an annotation of type MKUserLocation to the map.

The addition of the MKUserLocation annotation object to the map is reported by the delegate in the same way that custom annotations are. If you want to associate a custom annotation view with the user’s location, you should return that view from your delegate object’s mapView:viewForAnnotation: method. If you want to use the default annotation view, return nil from that method. To learn more about adding annotations to a map, see Annotating Maps.

听起来不错。但是后来...

import UIKit
import MapKit

class ViewController: UIViewController {

    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        //set initial location in Honolulu
        //let initialLocation = CLLocation(latitude: 21.282778, longitude: -157.829444)

        mapView.showsUserLocation = true
        let initialLocation = mapView.userLocation.location

        centerMapOnLocation(initialLocation)

        //        let artwork = Artwork(title: "King David Kalakaua", locationName: "Waikiki Gateway Park", discipline: "Sculpture", coordinate: CLLocationCoordinate2D(latitude: 21.283921, longitude: -157.831661))

        //        mapView.addAnnotation(artwork)
        //
        //        mapView.delegate = self
    }

    let regionRadius: CLLocationDistance = 1000
    func centerMapOnLocation(location: CLLocation){
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius * 2.0, regionRadius * 2.0)
        mapView.setRegion(coordinateRegion,animated:true)
    }
}

我有一个 fatal error: unexpectedly found nil while unwrapping an Optional value。我不明白为什么。如果我手动设置位置 - 当然没问题。但是在文档中写到它将在地图上添加注释。没有添加注释,它崩溃了。不使用 CLLocationManager 是不是可以获取用户坐标?

您是否已请求用户允许您的应用使用定位服务? Apple 的文档可以帮助您解决这个问题。查看下面的示例代码以帮助您入门:

private func beginLocationUpdates() {
    // Request location access permission
    _locationManager!.requestWhenInUseAuthorization()

    // Start observing location
    _locationManager!.startUpdatingLocation()
}