skip to Main Content

I have a problem with the Users Location.

When im trying to build the program it gets this error code: (Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value)

My code:



import UIKit
import MapKit
   


class ViewController: UIViewController {
    
    private let locationManager = CLLocationManager()
    private var currentCoordinate: CLLocationCoordinate2D?
    
    @IBOutlet weak var mapView: MKMapView!
    override func viewDidLoad() {
        super.viewDidLoad()
        configerLocationServices()
    }
    
    private func configerLocationServices() {
        locationManager.delegate = self
        
        let status = CLLocationManager.authorizationStatus()
        
        if status == .notDetermined {
            locationManager.requestWhenInUseAuthorization()
        } else if status == .authorizedAlways || status == .authorizedWhenInUse {
            beginLocationUpdates(locationManager: locationManager)
        }
    }
    
    private func beginLocationUpdates(locationManager: CLLocationManager) {
        mapView.showsUserLocation = true //<--- the problem is here
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
    }
    
    private func zoomToLastestLocation(with coordinate: CLLocationCoordinate2D) {
        let zoomRegion = MKCoordinateRegion(center: coordinate, latitudinalMeters: 10000, longitudinalMeters: 10000)
        mapView.setRegion(zoomRegion, animated: true)
    }
}

extension ViewController: CLLocationManagerDelegate {
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("Did get latest Location")
        
        guard let latestLocation = locations.first else { return }
        
        if currentCoordinate == nil {
            zoomToLastestLocation(with: latestLocation.coordinate)
        }
            
        currentCoordinate = latestLocation.coordinate
        
    }
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        print("The Status changed")
        if status == .authorizedAlways || status == .authorizedWhenInUse {
            self.beginLocationUpdates(locationManager: manager)
        }
    }
}

I don’t know what im doing wrong, has anyone the solution?

Thank you in advance.

2

Answers


  1. Chosen as BEST ANSWER

    I have now an other code for the same thing it is shorter than the old one.

    Here is the code:

    import UIKit import MapKit import CoreLocation

    class ViewController: UIViewController {

    @IBOutlet var mapView: MKMapView!
    
    let locationManager = CLLocationManager()
    
    override func viewDidLoad() {
            super.viewDidLoad()
        
        locationManager.requestWhenInUseAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.startUpdatingLocation()
        
            mapView.showsUserLocation = true // <--- Crash
        }
    

    }

    And now it gets the same problem as the old one :(


  2.  private func setNewLoaction(lat:CLLocationDegrees,long:CLLocationDegrees,markerTitle:String){
            
            let center = CLLocationCoordinate2D(latitude: lat, longitude: long)
            let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: long, zoom: 15)
            self.googleMapsView?.camera = camera
            self.googleMapsView?.isMyLocationEnabled = true
            let marker = GMSMarker(position: center)
            marker.map = self.googleMapsView
            marker.title = markerTitle
            locationManager.stopUpdatingLocation()
            
        }
        
        //MARK:- MAP VIEW
        
        private func setUpMap(){
            
            locationManager.delegate = self
            locationManager.requestWhenInUseAuthorization()
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
            self.googleMapsView = GMSMapView (frame: CGRect(x: 0, y: 0, width: self.view.frame.width-30, height: self.mapView.frame.height))
            self.googleMapsView?.settings.compassButton = true
            self.googleMapsView?.isMyLocationEnabled = true
            self.googleMapsView?.settings.myLocationButton = true
            self.mapView.addSubview(self.googleMapsView!)
        }
    

    I have called setUpMap in ViewDidload and this setLoaction function in GMSAutocompleteViewControllerDelegate =:

      func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
        
                
                destinationField.text = place.formattedAddress
                destinationLatitude = place.coordinate.latitude
                destinationLongitutude = place.coordinate.longitude
                setNewLoaction(lat:  destinationLatitude!, long: destinationLongitutude!, markerTitle: "Destination Location")
                
           
            dismiss(animated: true, completion: nil)
        }
    

    you can call this anywhere as per you need, do remember to turn on location when asked for permission and if using in simlulator go to Features/Loaction/custom Location

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search