Google地方信息API无法按预期运行

时间:2017-10-31 10:20:41

标签: ios xcode google-places-api google-places

我正在关注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("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")
        }
    }
})
}

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

  

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

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

令人困惑,因为我一步一步地按照教程进行操作。我正在使用启用了“位置服务”的物理设备测试应用程序。

知道我可能做错了吗?

或者是因为文档不是最新的?

2 个答案:

答案 0 :(得分:4)

  

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

这会指向您的答案。要让Google商家信息发挥作用,您需要致电requestWhenInUseAuthorization()申请使用定位服务。这将提示用户授予应用程序使用位置服务的权限。

有关详细信息,请参阅Apple Docs

修改

您应该对您创建的CLLocationManager保持强引用,以便在函数退出时不会取消分配。

  

"创建CLLocationManager类的实例,并在应用程序的某个位置存储对它的强引用。   在涉及该对象的所有任务完成之前,需要保留对位置管理器对象的强引用。由于大多数位置管理器任务以异步方式运行,因此将位置管理器存储在本地变量中是不够的。"

取自CLLocationManager Docs

示例

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

  override func viewDidLoad()
  {
    super.viewDidLoad()

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

答案 1 :(得分:0)

1。请求用户位置使用授权

requestWhenInUseAuthorization()requestAlwaysAuthorization()根据您的要求。

2。Info.plist中,添加以下键:

一个。 NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription

NSLocationAlwaysAndWhenInUseUsageDescription

示例:

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

    override func viewDidLoad()
    {
        super.viewDidLoad()
        locationManager.requestWhenInUseAuthorization()
        locationManager.delegate = self
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus)
    {

    }
}