Поток 1: Неустранимая ошибка: неожиданно обнаружено значение nil при неявном развертывании необязательного значения с помощью CoreLocation - PullRequest
0 голосов
/ 12 июля 2020

Я новичок в swift и пытаюсь понять, почему я получаю нулевое значение при запуске этой программы. Я попытался добавить func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [CLLocation]!), но это не сработало. Любая помощь будет принята с благодарностью. Спасибо

Вот код (PS: Это значение переменной locManager: var locManager = CLLocationManager()

override func viewDidLoad() {
        super.viewDidLoad()
        tableView.backgroundColor = UIColor.systemGreen
        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableView.automaticDimension
        
        locManager.requestWhenInUseAuthorization()
        func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [CLLocation]!) {
            let locationZoom = locations.last as! CLLocation
            
        }
        if CLLocationManager.authorizationStatus() == .authorizedWhenInUse || CLLocationManager.authorizationStatus() ==  .authorizedAlways
        {
            currentLocation = locManager.location
            //getting locations
            let longa = currentLocation.coordinate.longitude ***<- (Error occurring at this line)*** 
            let latta = currentLocation.coordinate.latitude
            nearbyLocations1(latitude: latta, longitude: longa) { (longitude, latitude, name, vicinity) in
                       
                    print("name 1 is ", name)
                   }
            nearbyLocations2(latitude: latta, longitude: longa) { (longitude, latitude, name, vicinity) in
                print("name 2 is ", name)
            }
            
        } 
        
    
    }

Ответы [ 2 ]

1 голос
/ 12 июля 2020

Есть две основные проблемы:

  1. Метод didUpdateLocations должен быть объявлен на верхнем уровне класса (на том же уровне, что и viewDidLoad) и весь код для обработки расположение должно быть внутри этого метода

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [CLLocation]!) {
         guard let currentLocation = locations.last else { return }
         //getting locations
         let longa = currentLocation.coordinate.longitude 
         let latta = currentLocation.coordinate.latitude
         nearbyLocations1(latitude: latta, longitude: longa) { (longitude, latitude, name, vicinity) in                       
             print("name 1 is ", name)
         }
         nearbyLocations2(latitude: latta, longitude: longa) { (longitude, latitude, name, vicinity) in
             print("name 2 is ", name)
         }
    }
    
Чтобы получить местоположения, вы должны установить делегата менеджера местоположения на self и позвонить startUpdatingLocation()
1 голос
/ 12 июля 2020

Вероятно, currentLocation = nil. Используйте

if let currentLocation = locManager.location {
    // Code for currentLocation != nil
} else {
    // Code for currentLocation == nil
}

или что-то подобное.

...