Диспетчер местоположения Отображает местоположение по умолчанию даже до предоставления разрешений GPS

Приложение запускается и отображает адрес в журналах даже до того, как будут предоставлены разрешения для GPS.

Вот мой код:

 override func viewDidLoad() {
    super.viewDidLoad()

    //Setting up the Location Manager.
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()

    //Showing user location on the map as a blue dot.
    self.theMap.showsUserLocation = true

    //Setting the delegate for the map view.
    self.theMap.delegate = self
}


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

    //Getting the last recorded location.
    let location = locations.last
    let ceter = CLLocationCoordinate2D(latitude:   (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!)

    //Setting the region of the map.
    let region = MKCoordinateRegion(center: ceter, span: MKCoordinateSpanMake(0.01, 0.01))

    //Assigning the region to the map.
    self.theMap.setRegion(region, animated: true)

    //Stop updating the location.
    self.locationManager.stopUpdatingLocation()

}


func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
    //Getting the center coordinate of the screen.
    let thecenter = mapView.centerCoordinate

    //Storing latitude & longitude in seperate variables.
    let centerLat = thecenter.latitude
    let centerlon = thecenter.longitude

    //Converting CLLocationCoordinate2D to CLLocation.
    let movedMap: CLLocation = CLLocation(latitude: centerLat, longitude: centerlon)

    //Performing Reverse GeoCoding to retrieve address from Coordinates.
    CLGeocoder().reverseGeocodeLocation(movedMap) { (placemarks, error) -> Void in

        //Checking for error.
        if(error != nil) {
            print(error)
        }else{

            //Taking the first coordinates among the lot & storing in variable 'p'.
            if let p = placemarks?.last {

                //Unwrapping Optional Strings.
                let roadno = p.subThoroughfare ?? ""

                //Checking if subThoroughfare exists.
                if(p.subThoroughfare != nil) {

                    //Unwrapping Optional Strings.
                    let thoroughfare = p.thoroughfare ?? ""
                    let subLocality = p.subLocality ?? ""
                    let locality = p.locality ?? ""
                    let administrativeArea = p.administrativeArea ?? ""
                    let postalCode = p.postalCode ?? ""
                    let country = p.country ?? ""

                    let address = " \(roadno) \r \(thoroughfare) \r \(subLocality) \r \(locality) \(administrativeArea) \(postalCode) \r \(country)"
                    print(address)

                   //Assigning the address to the address label on the map.
                   self.addressLabel.text = " \(roadno) \r \(thoroughfare) \r \(subLocality) \r \(locality) \(administrativeArea) \(postalCode) \r \(country)"

                }else{

                    //Unwrapping Optional Strings.
                    let thoroughfare = p.thoroughfare ?? ""
                    let subLocality = p.subLocality ?? ""
                    let locality = p.locality ?? ""
                    let administrativeArea = p.administrativeArea ?? ""
                    let postalCode = p.postalCode ?? ""
                    let country = p.country ?? ""

                    let address = " \(roadno) \r \(thoroughfare) \r \(subLocality) \r \(locality) \(administrativeArea) \(postalCode) \r \(country)"

                    print(address)
                    //Assigning the address to the address label on the map.
                    self.addressLabel.text = " \(thoroughfare) \r \(subLocality) \r \(locality) \(administrativeArea) \(postalCode) \r \(country)"
                }
            }
        }
    }
}

Я уверен, что моя ошибка связана с функцией regionDidChangeAnimated(), но я не могу понять, почему это обратное геокодирование координат, даже до того, как будут даны разрешения GPS.

* Отредактировано

Это новое сообщение об ошибке, которое я иногда получаю при запуске проекта.

Попытка запустить обновление местоположения MapKit без запроса авторизации местоположения. Сначала необходимо вызвать - [CLLocationManager requestWhenInUseAuthorization] или - [CLLocationManager requestAlwaysAuthorization].

Вот снимок экрана с ошибкой.


person Cedan Misquith    schedule 30.11.2015    source источник


Ответы (2)


Итак, я как бы нашел решение проблемы, с которой столкнулся. Я не знаю, правильное ли это решение, но при этом ошибка исчезла, и карта работает нормально.

override func viewDidLoad() {
    super.viewDidLoad()

    let coordinate:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0, longitude: 0)
    let span = MKCoordinateSpanMake(100, 80)
    let region = MKCoordinateRegionMake(coordinate, span)
    self.theMap.setRegion(region, animated: true)


    //Setting up the Location Manager.
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()

    //Showing user location on the map as a blue dot.
    self.theMap.showsUserLocation = true

    //Setting the delegate for the map view.
    self.theMap.delegate = self

}

Итак, что я сделал здесь, это в основном инициализировал карту до 0 широты и 0 долготы и установил регион в viewDidLoad (), и ошибка исчезла. Если по какой-либо причине это неправильное решение, дайте мне знать, каково точное решение этой проблемы.

person Cedan Misquith    schedule 03.12.2015

Я думаю, что большая часть вашей проблемы заключается в том, что вы запускаете обновление местоположения и показываете текущее положение в представлении карты до, чтобы убедиться, что:

  1. Службы геолокации включены для устройства
  2. У вашего приложения есть разрешение на их использование

Вот почему вы получаете сообщение MapKit.

Убедитесь, что оба требования выполнены перед использованием служб геолокации с CLLocationManager.locationServicesEnabled() и CLLocationManager.authorizationStatus().

Напоминаем (я часто об этом забываю): убедитесь, что в вашем Info.plist есть соответствующий ключ описания использования, один из NSLocationWhenInUseUsageDescription или NSLocationAlwaysUsageDescription.

person caseynolan    schedule 30.11.2015
comment
Спасибо за ответ .... Я попробовал два упомянутых вами пункта, но по какой-то причине я все еще получаю ту же ошибку, и я указал оба ключа описания NSLocationWhenInUseUsageDescription и NSLocationAlwaysUsageDescription в Info.plist - person Cedan Misquith; 01.12.2015