OStack程序员社区-中国程序员成长平台

标题: ios - Google Places API 未按预期工作 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 15:51
标题: ios - Google Places API 未按预期工作

我正在关注 Google Places API for IOS查看用户当前位置的教程。

我在教程中使用了相同的代码如下:

var placesClient: GMSPlacesClient!

// Add a pair of UILabels in Interface Builder, and connect the outlets to these variables.
@IBOutlet weak var nameLabel: UILabel!

@IBOutlet weak var addressLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    placesClient = GMSPlacesClient.shared()
}

// Add a UIButton in Interface Builder, and connect the action to this function.
@IBAction func getCurrentPlace(_ sender: UIButton) {

placesClient.currentPlace(callback: { (placeLikelihoodList, error) -> Void in
    if let error = error {
        print("ick Place error: \(error.localizedDescription)")
        return
    }

    self.nameLabel.text = "No current place"
    self.addressLabel.text = ""

    if let placeLikelihoodList = placeLikelihoodList {
        let place = placeLikelihoodList.likelihoods.first?.place
        if let place = place {
            self.nameLabel.text = place.name
            self.addressLabel.text = place.formattedAddress?.components(separatedBy: ", ")
                .joined(separator: "\n")
        }
    }
})
}

但我在控制台中收到以下错误:

Pick Place error: The operation couldn’t be completed. The Places API could not find the user's location. This may be because the user has not allowed the application to access location information.

注意:我在 info.plist 文件中设置了 NSLocationWhenInUseUsageDescription 键(隐私 - 使用时的位置使用说明)。

很迷惑,因为我是按照教程一步一步来的。并且正在使用启用了“位置服务”的物理设备测试应用程序。

知道我可能做错了什么吗?

还是因为文档不是最新的?



Best Answer-推荐答案


This may be because the user has not allowed the application to access location information.

这会指向您的答案。要使 Google Places 正常工作,您需要通过调用 requestWhenInUseAuthorization() 请求使用定位服务。这将提示用户授予该应用使用定位服务的权限。

请引用Apple Docs了解更多信息。

编辑

您应该保留对您创建的 CLLocationManager 的强引用,这样它就不会在您的函数退出时被释放。

"Create an instance of the CLLocationManager class and store a strong reference to it somewhere in your app. Keeping a strong reference to the location manager object is required until all tasks involving that object are complete. Because most location manager tasks run asynchronously, storing your location manager in a local variable is insufficient."

取自CLLocationManager Docs

示例

class LocationViewController: UIViewController, CLLocationManagerDelegate { 
  let locationManager = CLLocationManager()

  override func viewDidLoad()
  {
    super.viewDidLoad()

    locationManager.delegate = self
    if CLLocationManager.authorizationStatus() == .notDetermined
    {
       locationManager.requestWhenInUseAuthorization()
    }
  }
}

关于ios - Google Places API 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47032927/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4