Google Places API 未按预期工作

Beh*_*ahi 3 xcode ios google-places-api google-places

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

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

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("Pick 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")
        }
    }
})
}
Run Code Online (Sandbox Code Playgroud)

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

Pick Place 错误:操作无法完成。Places API 找不到用户的位置。这可能是因为用户没有允许应用程序访问位置信息。

注意:我已经NSLocationWhenInUseUsageDescriptioninfo.plist文件中设置了密钥(隐私 - 使用时的位置使用说明)。

这很令人困惑,因为我一步一步地遵循了教程。并且正在使用启用了“位置服务”的物理设备测试应用程序。

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

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

Rhu*_*len 6

这可能是因为用户没有允许应用程序访问位置信息。

这将您指向您的答案。要使用 Google 地方信息,您需要通过调用 请求使用位置服务requestWhenInUseAuthorization()。这将提示用户授予应用程序使用位置服务的权限。

有关更多信息,请参阅Apple 文档

编辑

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

“创建一个 CLLocationManager 类的实例,并将对它的强引用存储在应用程序的某个位置。在涉及该对象的所有任务完成之前,需要保持对位置管理器对象的强引用。因为大多数位置管理器任务都是异步运行的,因此存储您的局部变量中的位置管理器是不够的。”

取自CLLocationManager 文档

例子

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

  override func viewDidLoad()
  {
    super.viewDidLoad()

    locationManager.delegate = self
    if CLLocationManager.authorizationStatus() == .notDetermined
    {
       locationManager.requestWhenInUseAuthorization()
    }
  }
}
Run Code Online (Sandbox Code Playgroud)