Я работаю над проектом на основе 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.")
}
}