Find city name and country from latitude and longitude in Swift

前端 未结 11 1940
既然无缘
既然无缘 2020-12-12 22:58

I\'m working on application in Swift3 and I have letter problem i can\'t find the answer for it.

How can I know city name and country short names base on latitud

11条回答
  •  有刺的猬
    2020-12-12 23:17

    Add this extension in your swift file.

    extension CLLocation {
    func fetchAddress(completion: @escaping (_ address: String?, _ error: Error?) -> ()) {
        CLGeocoder().reverseGeocodeLocation(self) {
            let palcemark = $0?.first
            var address = ""
            if let subThoroughfare = palcemark?.subThoroughfare {
                address = address + subThoroughfare + ","
            }
            if let thoroughfare = palcemark?.thoroughfare {
                address = address + thoroughfare + ","
            }
            if let locality = palcemark?.locality {
                address = address + locality + ","
            }
            if let subLocality = palcemark?.subLocality {
                address = address + subLocality + ","
            }
            if let administrativeArea = palcemark?.administrativeArea {
                address = address + administrativeArea + ","
            }
            if let postalCode = palcemark?.postalCode {
                address = address + postalCode + ","
            }
            if let country = palcemark?.country {
                address = address + country + ","
            }
            if address.last == "," {
                address = String(address.dropLast())
            }
            completion(address,$1)
           // completion("\($0?.first?.subThoroughfare ?? ""), \($0?.first?.thoroughfare ?? ""), \($0?.first?.locality ?? ""), \($0?.first?.subLocality ?? ""), \($0?.first?.administrativeArea ?? ""), \($0?.first?.postalCode ?? ""), \($0?.first?.country ?? "")",$1)
        }
    }
    

    }

    And then call it on any of the CLLocation object.

    Eg:

     (myLocation as? CLLocation)!.fetchAddress { (address, error) in
                            guard let address = address, error == nil else                              
    {return }
    

提交回复
热议问题