使用数据进行 Swift 反向地理编码

标签 swift variables geocode

我已根据我的位置成功获取当前地址详细信息。它完美打印。让我困惑的是我如何从这个调用中提取数据。我尝试过将邮政编码/邮政编码作为本地变量甚至全局变量传递,但没有任何乐趣。数据似乎仅存在于该调用中。我如何在其他地方使用它?

// Get Address Information
    let geoCoder = CLGeocoder()
    let newLocation = CLLocation(latitude: valueLatitude, longitude: valueLongitude)
    geoCoder.reverseGeocodeLocation(newLocation, completionHandler: {(placemarks: [AnyObject]!, error: NSError!) in
        if error != nil {
            println("Geocode failed with error: \(error.localizedDescription)")
        }
        if placemarks.count > 0 {
            let placemark   = placemarks[0] as! CLPlacemark
            let addressDictionary = placemark.addressDictionary
            let address     = addressDictionary[kABPersonAddressStreetKey] as! NSString
            let city        = addressDictionary[kABPersonAddressCityKey] as! NSString
            let state       = addressDictionary[kABPersonAddressStateKey] as! NSString
            let postcode    = addressDictionary[kABPersonAddressZIPKey] as! NSString
            let country     = addressDictionary[kABPersonAddressCountryKey] as! NSString

            println("\(address) \(city) \(state) \(postcode) \(country)") }
    })

最佳答案

您的问题很可能是由于verseGeocodeLocation是向Apple服务器发出的异步请求造成的。

需要发生的是:

  1. 您调用reverseGeocodeLocation
  2. reverseGeocodeLocation 完成,开始完成,调用传递您刚刚恢复的地标的方法。

为了做到这一点:

@IBAction func btnInsertClicked(sender: AnyObject) { 
    var locationRecord: LocationRecord = LocationRecord() 

    // Get Address Information 
    let geoCoder = CLGeocoder() 
    let newLocation = CLLocation(latitude: valueLatitude, longitude: valueLongitude) 
    geoCoder.reverseGeocodeLocation(newLocation, completionHandler:
        {(placemarks: [AnyObject]!, error: NSError!) in 
            if error != nil { 
                println("Geocode failed with error: (error.localizedDescription)") 
            }

            if placemarks.count > 0 { 
                let myPlacemark = placemarks[0] as! CLPlacemark 

                // Here call the method that uses myPlacemark
                self.myAwesomeMethod(placemarks[0] as! CLPlacemark)
            } else {
                println("No placemark")
            } 
        })
}

您需要在代码中使用它的位置:

func myAwesomeMethod(placemark: CLPlacemark) {
    // Do stuff with placemark
}

今晚我才能拿到我的 Mac,但如果这不起作用,请发表评论,我们会解决这个问题

关于使用数据进行 Swift 反向地理编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30909292/

相关文章:

php - 将变量插入 header 位置 PHP

android - 反向地理编码中的异常

php - HTTP 请求失败 - Google map

swift 'FIRInvalidArgumentException' ,原因 : 'Unsupported type: NSURL (found in field AccountTypeImageURL)'

ios - swift 错误 : Cannot pass immutable value as inout argument: 'pChData' is a 'let' constant

swift - 无法更新数组中字典中的值?

c - 只是想确保我理解外部变量是什么

swift - Cocoa 绘制可 ScrollView 的困境

javascript - 在 Javascript 中拆分和分配多个值的更好方法?

ruby-on-rails - 如何使用地理编码 gem 获取时区?