unwrapping issue I believe.

Not sure what the issue is as this code ran fine a week ago and ive made no changes.


let sourcePlacemark = MKPlacemark(coordinate: sourceCoordinates! )

//gives the following

///Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

//the full code for the view

let locationManager = CLLocationManager()
   
   
   
    override func viewDidLoad() {
       
        super.viewDidLoad()
        WOLMenu.target = self.revealViewController()
        WOLMenu.action = #selector(SWRevealViewController.revealToggle(_:))
        WOLMapView.delegate = self
        WOLMapView.showsScale = true
        WOLMapView.showsPointsOfInterest = true
        WOLMapView.showsUserLocation = true
       
        locationManager.requestAlwaysAuthorization()
        locationManager.requestWhenInUseAuthorization()
       
       
       
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
           
        }
       
       
       
        let sourceCoordinates = locationManager.location?.coordinate
        let destCoordinates = CLLocationCoordinate2DMake( 32.4208, -104.2400)
       
       
       
        let sourcePlacemark = MKPlacemark(coordinate: sourceCoordinates! )
        let destPlacemark = MKPlacemark(coordinate: destCoordinates)
       
       
       
        let sourceItem = MKMapItem(placemark: sourcePlacemark)
        let destItem = MKMapItem(placemark: destPlacemark)
       
       
       
        let directionRequest = MKDirectionsRequest()
        directionRequest.source = sourceItem
        directionRequest.destination = destItem
        directionRequest.transportType = .automobile
       
       
       
        let directions = MKDirections(request: directionRequest)
        directions.calculate(completionHandler: {
        response, error in
        guard let response = response else {
                if let error = error {
                    print("Something went wrong")
                   
                }
               
                return
               
            }
           
           
           
            let route = response.routes[0]
            self.WOLMapView.add(route.polyline, level: .aboveRoads)
           
            let rekt = route.polyline.boundingMapRect
            self.WOLMapView.setRegion(MKCoordinateRegionForMapRect(rekt), animated: true)
           
        })
        self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
       
    }
   
   
   
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKPolylineRenderer(overlay: overlay)
        renderer.strokeColor = UIColor.black
        renderer.lineWidth = 5.0
       
        return renderer
       
    }
   
   
   
    override var prefersStatusBarHidden: Bool {
        return true 
    }
   
   
   
}

On what line of code do you get the error?

42 it is also the first line as i singled it out

You have a section of code that depends on whether location services are enabled and, only if true, requests updates.

A few llines after that, you force unwrap a variable that will be nil if no location data has been retrieved.


It seems like a lot more code should be inside the "if CLLocationManager.locationServicesEnabled() {" section.


Better still might be an "if let sourceCoordinates = locationManager.location?.coordinate { ... }" to take care of whatever makes it nil.

All of the reqs are in plist and capabilitys... its very frusterating to hve an app working and then the build just fails without any changes to the app

this is the full code

import Foundation
import MapKit
import CoreLocation
class World : UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
   
    @IBOutlet weak var WOLMapView: MKMapView!
    @IBOutlet weak var WOLMenu: UIBarButtonItem!
    @IBAction func GoogleButton(sender: AnyObject) {
       
        if let url = URL(string: "https:/
           
            UIApplication.shared.open(url, options: [:])
           
        }
       
    }
   
   
    let locationManager = CLLocationManager()
   
   
   
    override func viewDidLoad() {
       
        super.viewDidLoad()
        WOLMenu.target = self.revealViewController()
        WOLMenu.action = #selector(SWRevealViewController.revealToggle(_:))
        WOLMapView.delegate = self
        WOLMapView.showsScale = true
        WOLMapView.showsPointsOfInterest = true
        WOLMapView.showsUserLocation = true
       
        locationManager.requestAlwaysAuthorization()
        locationManager.requestWhenInUseAuthorization()
       
       
       
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
           
        }
       
       
       
        let sourceCoordinates = locationManager.location?.coordinate
        let destCoordinates = CLLocationCoordinate2DMake( 32.4208, -104.2400)
       
       
       
        let sourcePlacemark = MKPlacemark(coordinate: sourceCoordinates! )
        let destPlacemark = MKPlacemark(coordinate: destCoordinates)
       
       
       
        let sourceItem = MKMapItem(placemark: sourcePlacemark)
        let destItem = MKMapItem(placemark: destPlacemark)
       
       
       
        let directionRequest = MKDirectionsRequest()
        directionRequest.source = sourceItem
        directionRequest.destination = destItem
        directionRequest.transportType = .automobile
       
       
       
        let directions = MKDirections(request: directionRequest)
        directions.calculate(completionHandler: {
        response, error in
        guard let response = response else {
                if let error = error {
                    print("Something went wrong")
                   
                }
               
                return
               
            }
           
           
           
            let route = response.routes[0]
            self.WOLMapView.add(route.polyline, level: .aboveRoads)
           
            let rekt = route.polyline.boundingMapRect
            self.WOLMapView.setRegion(MKCoordinateRegionForMapRect(rekt), animated: true)
           
        })
        self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
       
    }
   
   
   
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKPolylineRenderer(overlay: overlay)
        renderer.strokeColor = UIColor.black
        renderer.lineWidth = 5.0
       
        return renderer
       
    }
   
   
   
    override var prefersStatusBarHidden: Bool {
        return true 
    }
   
   
   
}
Accepted Answer

But that isn't what happened. The app works the same as it did before. It was wrong a week ago, but you were just unlucky it didn't fail while you were debugging a week ago.


There are, in effect, two bugs in your code:


1. The "startUpdatingLocation" function is asynchonous, so its effects may not be produced immediately. According the documentation (https://developer.apple.com/documentation/corelocation/cllocationmanager/1423750-startupdatinglocation):


"Calling this method causes the location manager to obtain an initial location fix (which may take several seconds)"


so if you want to wait until a location is obtained, you should watch via the "locationManager:didUpdateLocations:" delegate method.


2. You allowed an optional value to "escape" from line 37 (of your original code), but the later code didn't expect the nil value. As pmills suggested, you should resolve the optional right at line 37, so that "sourceCoordinates" is not of optional type.


Inserting "?" operators randomly to get your code to compile is a Bad Idea, as this whole episode shows.

unwrapping issue I believe.
 
 
Q