Fabio
Fabio

Reputation: 1973

CLLocationManager fatal error: unexpectedly found nil while unwrapping an Optional value Swift

I have a problem because my app crash when i try to get position user and have permission in my .plist this my code.

import UIKit
import MapKit
import CoreLocation

class mapClass : UIViewController,MKMapViewDelegate,CLLocationManagerDelegate{

    var location4 = CLLocation()
    var lm  = CLLocationManager ()

    @IBOutlet  var propMapa: MKMapView!

    lm.delegate=self
    lm.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    lm.distanceFilter = kCLDistanceFilterNone
    lm.startUpdatingLocation()

    println("\(lm.location)") <---- nil

   location4 = lm.location <---- crash

}

Log: fatal error: unexpectedly found nil while unwrapping an Optional value

Upvotes: 3

Views: 3002

Answers (3)

Acces control may not be done yet. You can check if autorisation is available.

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    if CLLocationManager.locationServicesEnabled() {
        switch CLLocationManager.authorizationStatus() {
        case .notDetermined, .restricted, .denied:
            print("No access")
        case .authorizedAlways, .authorizedWhenInUse:
            let sourceCoordinate = locationManager.location?.coordinate
            showRouteOnMap(pickupCoordinate: sourceCoordinate!, destinationCoordinate: CLLocationCoordinate2DMake(41.037141,28.9834662))
        }
    } else {
        print("Location services are not enabled")
    }
}

Upvotes: 0

Ramkumar Paulraj
Ramkumar Paulraj

Reputation: 1943

import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController,MKMapViewDelegate,CLLocationManagerDelegate
{
    @IBOutlet weak var mapView: MKMapView!
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var searchButton: UIButton!
    let locationManager = CLLocationManager()
    var location:CLLocationCoordinate2D!

    override func viewDidLoad() {
        super.viewDidLoad()

        println("Search Button Clicked");
        mapView.showsUserLocation = true;
    }

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

    @IBAction func searchButtonClicked(sender:AnyObject)
    {
        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self

        locationManager.requestWhenInUseAuthorization()

        locationManager.startUpdatingLocation()
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

        println("delegate called")
        if manager.location != nil
        {
            println(locationManager.location.coordinate.latitude)
            let artwork = Artwork(title: "Ram",
                locationName: "Infotech",
                discipline: "Testing",
                coordinate: CLLocationCoordinate2D(latitude:manager.location.coordinate.latitude, longitude:manager.location.coordinate.longitude))

            mapView.addAnnotation(artwork)
        }

    }

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
    {

        println(error)
    }
}

Upvotes: 0

zisoft
zisoft

Reputation: 23078

After calling lm.startUpdatingLocation() the location manager calls didUpdateLocations() whenever it detects a location change, so you need to implement CLLocationManager::didUpdateLocations to retrieve the location:

import UIKit
import MapKit
import CoreLocation

class mapClass : UIViewController,MKMapViewDelegate,CLLocationManagerDelegate{

    var location4 = CLLocation()
    var lm  = CLLocationManager ()

    @IBOutlet  var propMapa: MKMapView!

    ...

    lm.delegate=self
    lm.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    lm.distanceFilter = kCLDistanceFilterNone
    lm.startUpdatingLocation()
}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

    let currentLocation = locations.last as CLLocation
    println(currentLocation)
    ...
}

Upvotes: 6

Related Questions