【问题标题】:While fetching nearby places from google places api. Getting an error The provided API key is invalid从 google places api 获取附近地点时。收到错误 提供的 API 密钥无效
【发布时间】:2018-06-09 11:32:54
【问题描述】:

我正在尝试获取附近的地点,但收到错误提供的 API 密钥无效。

//来自console.developers.google.com

我确实从控制台开发人员创建了项目,为 IOS 启用了 google places sdk,还生成了 API 密钥,并且从密钥限制中我选择了 IOS 应用程序并提供了我的密钥限制。

所以我的问题是我的代码有问题,或者需要做更多设置 console.developers.google.com

func getNearByPlace(place: String) {

    var strGoogleApi = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=53.2734, -7.778320310000026&radius=50000&keyword=\(place)&sensor=true&key=\(googleApiKey) "
    strGoogleApi = strGoogleApi.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!

    var urlRequest = URLRequest(url: URL(string: strGoogleApi)!)
    urlRequest.httpMethod = "GET"

    let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
        if error == nil {
            let jsonDict = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
            print("Json == \(jsonDict!)")
        } else {

        }
    }
    task.resume()
}

【问题讨论】:

    标签: ios google-maps google-places-api swift4


    【解决方案1】:

    您应该删除字符串中\(googleApiKey) 之后的尾随空格。 API 密钥后的空格会破坏验证。

    此外,Places API Web 服务的 API 密钥必须不同于您在 Maps iOS SDK 中使用的 API 密钥,因为 Web 服务不支持 iOS 应用限制。 Web 服务只能受后端服务器的 IP 地址限制。这意味着您应该安装一个中间服务器,该服务器向 Google 发送请求并将响应传递回您的应用程序,以保护您的 API 密钥,或者如果您直接从应用程序调用 Web 服务,则使用不受保护的密钥。后者是一个坏主意,因为它是一个安全漏洞。

    请查看以下解释关键系统的文章

    https://developers.google.com/maps/faq#keysystem

    我希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      不要忘记在应用程序中使用您的 API_KEY(_:didFinishLaunchingWithOptions:)

      GMSServices.provideAPIKey("YOUR_API_KEY") 
      

      如果您使用 Places API:

      GMSPlacesClient.provideAPIKey("YOUR_API_KEY")
      

      请参考公众号documentation

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-19
        • 1970-01-01
        • 2023-03-30
        • 2017-06-12
        • 2017-11-04
        • 1970-01-01
        • 2014-11-06
        • 1970-01-01
        相关资源
        最近更新 更多