【问题标题】:Swift UserLocation UITextFieldSwift UserLocation UITextField
【发布时间】:2018-02-18 00:26:52
【问题描述】:

嘿,有谁知道如何制作一个用用户当前地址填充 UITextField 的按钮?我对任何框架或 API 持开放态度,我只需要朝着正确的方向推进,也许是一个教程。谢谢。

【问题讨论】:

标签: ios swift core-location


【解决方案1】:

更新的解决方案:

要首先获取用户的经度和纬度位置,您必须

  1. import CoreLocation 添加到您的班级
  2. 在你的类声明中添加CLLocationManagerDelegate
  3. NSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescription 添加到您的info.plist 文件中。您只需按添加按钮并复制并粘贴其中之一即可。它应该自动更正为Privacy - Location When In Use Usage Description,然后您可以在其右侧的框中添加描述。当应用要求使用用户的位置时,该描述将出现在弹出窗口中。
  4. 然后您需要启动位置管理器。您可以使用

    let manager = CLLocationManager()
    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestAlwaysAuthorization()
    manager.startUpdatingLocation()
    
  5. 然后您可以使用获取用户的位置

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let locat = manager.location
    

    }

现在您有了用户的经度和纬度位置,您必须使用地理编码将其转换为地址。为此,您必须

  1. import AddressBookUI 添加到您的班级
  2. 创建CLGeocoder,例如let geocoder: CLGeocoder = CLGeocoder()
  3. 实现反向地理编码功能

    geocoder.reverseGeocodeLocation(locat!, completionHandler: {
        (placemarks, error) in
        if (error != nil) {
            //geocoding failed
        } else {
            let pm = placemarks! as [CLPlacemark]
    
            if pm.count > 0 {
                let pm = placemarks![0]
                let address = (pm.subThoroughfare + ", " + pm.thoroughfare + ", " + pm.locality + ", "  + pm.subLocality + ", " + pm.country + ", " + pm.postalCode)
                print(address)
                manager.stopUpdatingLocation()
            }
        }
    })
    

此函数获取我们之前已经计算出的用户当前位置,然后获取位置的每一位,正确排序,并将其打印到控制台中。然后它会停止更新用户的位置。

最后,您可以将 UIButton 的文本更改为包含地址的字符串。

【讨论】:

    猜你喜欢
    • 2015-10-08
    • 2020-02-17
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2019-10-29
    相关资源
    最近更新 更多