Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get city name by current latitude and longitude in swift

I'm trying to get city name from my current location coordiate by using CLGeocoder().reverseGeocodeLocation.

It gives me country name, street name, state and many other things but not city. Is there anything wrong with my code?

Here's my code:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations[0]
    CLGeocoder().reverseGeocodeLocation(location) { (placeMark, error) in
        if error != nil{
            print("Some errors: \(String(describing: error?.localizedDescription))")
        }else{
            if let place = placeMark?[0]{
                print("country: \(place.administrativeArea)")

                self.lblCurrentLocation.text = place.administrativeArea
            }
        }
    } }

I use the below code too. But doesn't work for me. Here's the another way.

        let geoCoder = CLGeocoder()
    let location = CLLocation(latitude: (self.locationManager.location?.coordinate.latitude)!, longitude: (self.locationManager.location?.coordinate.longitude)!)
    geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in

        // Place details
        var placeMark: CLPlacemark!
        placeMark = placemarks?[0]

        // Address dictionary
        print(placeMark.addressDictionary as Any)

        // Location name
        if let locationName = placeMark.addressDictionary!["Name"] as? NSString {
            print("locationName: \(locationName)")
        }
        // Street address
        if let street = placeMark.addressDictionary!["Thoroughfare"] as? NSString {
            print("street: \(street)")
        }
        // City
        if let city = placeMark.addressDictionary!["City"] as? NSString {
            print("city : \(city)")
        }
        // Zip code
        if let zip = placeMark.addressDictionary!["ZIP"] as? NSString {
            print("zip :\(zip)")
        }
        // Country
        if let country = placeMark.addressDictionary!["Country"] as? NSString {
            print("country :\(country)")
        }
    })

Please someone help me to get city name.

like image 298
Sptibo Avatar asked Mar 14 '18 11:03

Sptibo


People also ask

How get lat long from address in Swift?

geocodeAddressString(addressString) { (placemarks, error) in if error == nil { if let placemark = placemarks?[0] { let location = placemark. location! completionHandler(location. coordinate, nil) return } } completionHandler(kCLLocationCoordinate2DInvalid, error as NSError?) } }

How do I ask a user for location in Swift?

You need to add a key NSLocationWhenInUseUsageDescription in yours info. plist file and in the value you write something that you want to show the user in the popup dialog. You need to test it on a real device cause Simulator accepts only custom locations. Select the Simulator -> Debug -> Location -> Custom Location...


1 Answers

The field is called locality

 if let locality = placeMark.addressDictionary!["locality"] as? NSString {
            print("locality :\(locality)")
        }

Locality Apple docs

https://developer.apple.com/documentation/corelocation/clplacemark/1423507-locality?language=objc

CLPlacemark

https://developer.apple.com/documentation/corelocation/clplacemark?language=objc

Update:

Try this

import Foundation
import CoreLocation

let geoCoder = CLGeocoder()
let location = CLLocation(latitude: 40.730610, longitude:  -73.935242) // <- New York

geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, _) -> Void in

    placemarks?.forEach { (placemark) in

        if let city = placemark.locality { print(city) } // Prints "New York"
    }
})
like image 108
brduca Avatar answered Oct 04 '22 14:10

brduca