Get location name from Latitude & Longitude in iOS

前端 未结 12 1018
遥遥无期
遥遥无期 2020-11-28 07:30

I want to find current location name from latitude and longitude,

Here is my code snippet I tried but my log shows null value in all the places except in place

12条回答
  •  情歌与酒
    2020-11-28 07:58

    Swift 5

    import CoreLocation
    
    func printAddress() {
      if let lat = Double(30.710489), lat != 0.0, let long = Double(76.852386), long != 0.0 {
      // Create Location
      let location = CLLocation(latitude: lat, longitude: long)
      // Geocode Location
      CLGeocoder().reverseGeocodeLocation(location) { (placemarks, error) in
               // Process Response
               self.processResponse(withPlacemarks: placemarks, error: error)
             }
         }
    }
    
    private func processResponse(withPlacemarks placemarks: [CLPlacemark]?, error: Error?) {
           var address = ""
            if let error = error {
                address = "Unable to Reverse Geocode Location (\(error))"
            } else {
                if let placemarks = placemarks, let placemark = placemarks.first {
                    address = placemark.compactAddress ?? ""
                } else {
                    address = "No address found"
                }
            }
            print(address)
        }
    extension CLPlacemark {
    var compactAddress: String? {
        if let name = name {
            var result = name
    
            if let street = thoroughfare {
                result += ", \(street)"
            }
            if let city = locality {
                result += ", \(city)"
            }
            if let postalCode = postalCode {
                result += ", \(postalCode)"
            }
            if let country = country {
                result += ", \(country)"
            }
            return result
        }
    
        return nil
    }
    }
    // 2nd Way
    
    func updateLocation(lat:Double,long:Double) {
               CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: Double(lat), longitude: Double(long)), completionHandler: { (placemarks, error) -> Void in
                   if error != nil {
                       return
                   }
                   else {
                      var location = ""
                       let pm = placemarks![0]
                       if pm.addressDictionary!["FormattedAddressLines"] != nil    {
                           location =  "\n" + (pm.addressDictionary!["FormattedAddressLines"] as! NSArray).componentsJoined(by: ", ")
                       }else{
                           location = "\n" + "NO_ADDRESS_FOUND"
                       }
    
                   }
                   })
           }
    

提交回复
热议问题