'Coordinate Location in Swift returning nil when authorized

I'm trying to get the current coordinates of a user based on their location in Swift.

I've imported

import UIKit
import CoreLocation
import MapKit

And I've created two global variables called

var locationManager = CLLocationManager()
var currentLocation: CLLocation!

In my viewDidLoad() function, I have requested authorization from the user like this:

locationManager.requestWhenInUseAuthorization()

        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.startUpdatingLocation()
        }
        
        switch locationManager.authorizationStatus {
        case .restricted, .denied, .notDetermined:
            print("not determined")
            return
        case .authorizedAlways, .authorizedWhenInUse:
            print("authorized")
            currentLocation = locationManager.location
            print(currentLocation.coordinate.latitude)
            return
        default:
            print("default!")
        }

And in my info.plist file, I've added the location request description. However, when I run my application, it will print out authorized but when it tries to print the user location (the latitude, in this example). I get Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value. Why am I getting this error if I've made sure the location manager was authorized? Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source