如何通过单击按钮将My Geolocation发送到文本文件?

时间:2015-10-29 10:18:52

标签: ios xcode swift

我'我正在设计一个地理应用程序。 我想做这样的事情,比如通过点击按钮将我的位置发送到文本字段。

现在我写了这样的功能:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    print (locations)
    let UserLocation:CLLocation = locations[0]

    CLGeocoder().reverseGeocodeLocation(UserLocation) { (placemarks, error) -> Void in

        if error != nil {
            print(error)
        } else {
            let p = placemarks?.first

            print p


        }

    }


}

方法CLGeocoder帮助我从位置获取地址。 现在我想通过点击我的按钮将此地址发送到我的文本域

我应该将相同的代码写入

@IBAction func MyLocationBtn(sender: AnyObject) {


} 

或者我如何使用我的函数来获取数据?如果是的话,请你帮助我如何调用此功能并进入p

1 个答案:

答案 0 :(得分:1)

所以你有两个耗时的操作:

  1. 获取用户位置
  2. 从位置获取地址。
  3. 我认为您的方法是正确的,因为每当用户的位置发生变化时,您都会向CLCGeocoder询问信息。

    我假设您在ViewController中保留对LocationManager的引用。 在我看来,你可以试试:

    @IBAction func MyLocationBtn(sender: AnyObject) {
         let userLocation = locationManager.location // returns last user location
         if userLocation == nil {
               return 
         }
    
         CLGeocoder().reverseGeocodeLocation(userLocation) { (placemarks, error) -> Void in
    
            if error != nil {
               print(error)
            } else {
               let p = placemarks?.first
    
               self.yourTextField.text = ABCreateStringWithAddressDictionary(p.addressDictionary, true)
    
            }
    
        }
    } 
    

    您还可以在获得用户位置之前停用MyLocationBtn

     override func viewDidLoad() {
          super.viewDidLoad()
          YOUR_BUTTON.enabled = false
     }
    

    并在获得用户位置时启用它:

     func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
          print (locations)
          let UserLocation:CLLocation = locations[0]
          if UserLocation != nil {
                YOUR_BUTTON.enabled = true
          }
     }
    

    ABCreateStringWithAddressDictionarydocs

    修改

    如果您不想混淆用户(当互联网连接速度较低时),请尝试在用户点击按钮时显示活动指示符,并在获得地标时隐藏它。