Не получается мой текущий адрес из диспетчера местоположения в iOS - PullRequest
0 голосов
/ 21 февраля 2019

Я работаю над проектом на основе Google Maps API.Я хочу получить текущее местоположение и адрес пользователя с помощью Google API.Я использовал диспетчер местоположения, чтобы получить адрес пользователя, используя текущую широту и долготу пользователя.Он дает мне адрес, когда я устанавливаю местоположение моего симулятора в Сан-Франциско.Вот мой код:

locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
// Here you can check whether you have allowed the permission or not.

if CLLocationManager.locationServicesEnabled()
{
    switch(CLLocationManager.authorizationStatus())
    {
    case .authorizedAlways, .authorizedWhenInUse:
        print("Authorize.")
        let latitude: CLLocationDegrees = (coordinate.latitude)
        let longitude: CLLocationDegrees = (coordinate.longitude)
        print(coordinate.latitude,coordinate.longitude)

        let location = CLLocation(latitude: latitude, longitude: longitude) //changed!!!
        CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
            if error != nil {

                let alertController = UIAlertController(title: "Current Location", message: "\(error)", preferredStyle: .alert)
                let saveAction = UIAlertAction(title: "Ok", style: .default) { [unowned self] action in
                    self.dismiss(animated: true, completion: nil)

                    return

                }

                alertController.addAction(saveAction)

                self.present(alertController, animated: true, completion: nil)
                return

            }else if let country = placemarks?.first?.country,
                let city = placemarks?.first?.locality,

                let area = placemarks?.first?.subLocality,
                let street =  placemarks?.first?.thoroughfare,
                let number =  placemarks?.first?.subThoroughfare{
                print(country)
                print(city)
                print(area)
                print(street)
                print(number)

                let locationString = "\(street ?? "")-" + "\(number ?? "") ," + "\(area ?? "")"
                print(locationString)
                 UserDefaults.standard.set(locationString, forKey: "Address")
                let alertController = UIAlertController(title: "Current Location", message: "\(locationString)", preferredStyle: .alert)
                let saveAction = UIAlertAction(title: "Ok", style: .default) { [unowned self] action in
                    self.dismiss(animated: true, completion: nil)

                }


                alertController.addAction(saveAction)

                self.present(alertController, animated: true, completion: nil)
                }



        })
        break

    case .notDetermined:
        print("Not determined.")
        break

    case .restricted:
        print("Restricted.")
        break

    case .denied:
        print("Denied.")
    }
}

1 Ответ

0 голосов
/ 21 февраля 2019

Если вы работаете на симуляторах, вам нужно отредактировать свою схему, вероятно, поэтому вы всегда получаете адрес Сан-Франциско, перейдите в Product -> Scheme -> Edit Scheme, затем в открывшемся окне выберите «ОпцииВ первой настройке вы увидите, что для параметра «Местоположение по умолчанию» установлено значение «Сан-Франциско», просто измените его на «Нет» и повторите попытку

...