Display current location without using CLLocationManager

1k views Asked by At

I am new to iOS and I have a question about finding the current user location. I am reading in Apple documentation:

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.

And it sounds great. But then...

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)
    }
}

And I have a fatal error: unexpectedly found nil while unwrapping an Optional value. I don't get why. If I set the location manually - of course it is fine. But in the documentation it is written that it will add an annotation on the map. No annotation is added and it crashes. Isn't it possible to get the user coordinates without using the CLLocationManager?

1

There are 1 answers

1
John Difool On BEST ANSWER

Have you asked permissions to the user to let your app use the location services? The docs at Apple can help you with this. Look at the sample code below to get you started:

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

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