无法快速获取当前纬度和经度的城市名称

Spt*_*bo 6 ios currentlocation clgeocoder swift

我正在尝试使用CLGeocoder().reverseGeocodeLocation.

它给了我国家名称、街道名称、州和许多其他东西,但没有城市。我的代码有什么问题吗?

这是我的代码:

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
            }
        }
    } }
Run Code Online (Sandbox Code Playgroud)

我也使用下面的代码。但对我不起作用。这是另一种方式。

        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)")
        }
    })
Run Code Online (Sandbox Code Playgroud)

请有人帮我获取城市名称。

brd*_*uca 7

该字段称为局部性

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

本地 Apple 文档

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

CL地标

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

更新:

尝试这个

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"
    }
})
Run Code Online (Sandbox Code Playgroud)