Распечатать userLocation to textLabel - PullRequest
0 голосов
/ 11 февраля 2019

Я пытаюсь напечатать userLocation в textLabel, но мне не нужны точные значения долготы и широты, я просто хочу, например, название улицы, где находится текущее местоположение пользователя, или даже просто код подсказки.Вы знаете, что я имею в виду?

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

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    mapView.showsUserLocation = true
if CLLocationManager.locationServicesEnabled() == true {

        if CLLocationManager.authorizationStatus() == .restricted || CLLocationManager.authorizationStatus() == .denied ||  CLLocationManager.authorizationStatus() == .notDetermined {
            locationManager.requestWhenInUseAuthorization()
        }
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
        locationManager.startUpdatingLocation()
    } else {
        print("PLease turn on location services or GPS")
    }
 }

 //MARK:- CLLocationManager Delegates
func locationManager(_ manager: CLLocationManager,       
 didUpdateLocations locations: [CLLocation]) {
    self.locationManager.stopUpdatingLocation()
    let region = MKCoordinateRegion(center:  
 CLLocationCoordinate2D(latitude: locations[0].coordinate.latitude, 
 longitude: locations[0].coordinate.longitude), span: 
   MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002))
      //self.posizione.text = "latitude: " +  
      //String(location.coordinate.latitude) + ", longitude: " + 
     //String(location.coordinate.longitude)
    self.mapView.setRegion(region, animated: true)
}

Чтобы напечатать местоположение на ярлыке, который я пробовал:

self.posizione.text = "latitude: " +  
String(location.coordinate.latitude) + ", longitude: " + 
String(location.coordinate.longitude)

но, к сожалению, ярлык остается пустым ...

1 Ответ

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

Так что, если я вас правильно понимаю, вам нужны не долгота и широта, а название города и адрес улицы, по которой сейчас находится пользователь.

Чтобы получить их, сделайте следующее:

Сделайте так, чтобы ваш класс соответствовал CLLocationManagerDelegate и MKMapViewDelegate.Добавьте требуемое разрешение в файле Info.plist (расположение при использовании описания использования).

Чуть ниже вставки объявления класса:

    let locationManager = CLLocationManager()
    var scanLocation: String?

В вашей вставке viewDidLoad:

        //setting up location manager
    locationManager.requestWhenInUseAuthorization()
    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startUpdatingLocation()
    }

    //setting up the map view
    mapView.delegate = self
    mapView.mapType = .standard
    mapView.isZoomEnabled = true
    mapView.isScrollEnabled = true

А затем вызвать метод didUpdateLocations следующим образом:

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let lastLocation = locations.last {
        let geoCoder = CLGeocoder()

        //this is where you deal with the mapView to display current location
        let center = CLLocationCoordinate2D(latitude: lastLocation.coordinate.latitude, longitude: lastLocation.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
        mapView.setRegion(region, animated: true)

        let annotation = MKPointAnnotation()
        annotation.coordinate = manager.location!.coordinate
        annotation.title = "I know where you are"
        annotation.subtitle = "your current location"
        mapView.addAnnotation(annotation)

        //This is where you get the current street and city name
        geoCoder.reverseGeocodeLocation(lastLocation) { (placeMarks, error) in
            if error == nil {
                if let firstLocation = placeMarks?[0] {
                    self.locationManager.stopUpdatingLocation()

                    if let cityName = firstLocation.locality,
                        let street = firstLocation.thoroughfare {

                    self.scanLocation = "\(street), \(cityName)"
                    print("This is the current city name", cityName)
                    print("this is the current street address", street)

                    self.posizione.text = self.scanLocation!
                    }
                }
            }
        }
    }
}
...