Search code examples
swiftmkmapviewcllocation

Unwrapping optional for MKMap Location gives error


I'm trying to include a map in my application - following the instructions here. The problem is that I'm getting an error when setting the region - the line of code "let region = MKMap..." and I don't know why. Has anyone encountered this problem or know how to help? Thanks!

Code update:

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate {

    // MARK: Properties
    @IBOutlet weak var MapView: MKMapView!
    var locationManager = CLLocationManager.init()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        locationManager.requestWhenInUseAuthorization()

        MapView.mapType = .standard
        MapView.showsUserLocation = true
        MapView.showsScale = true
        MapView.showsCompass = true

        let span = MKCoordinateSpan.init(latitudeDelta: 0.0075, longitudeDelta: 0.0075)
        let region = MKCoordinateRegion.init(center: (locationManager.location?.coordinate)!, span: span)
        MapView.setRegion(region, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


} 

Error update: The line that causes the error is:

let region = MKCoordinateRegion.init(center: (locationManager.location?.coordinate)!, span: span)

and the error is:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)


Solution

  • Your code will always crash. You are saying:

        locationManager.requestWhenInUseAuthorization()
        // ...
        let region = MKCoordinateRegion.init(center: (locationManager.location?.coordinate)!, span: span)
    

    So you have given the location manager no instructions to start getting the device's location, but here you are force-unwrapping the location manager's location. Naturally, that location is nil, and naturally you crash.

    If your goal is to have the map show the user's location, then set the map's showsUserLocation or (better) its userTrackingMode and stop. Just stand back and let the map do its work. Do not fight the map view by trying to dictate its region; it knows better than you do how to display the user's location.