从 google 个地方 api 获取附近的地方。收到错误提供的 API 密钥无效

While fetching nearby places from google places api. Getting an error The provided API key is invalid

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

//来自console.developers.google.com

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

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

func getNearByPlace(地点:字符串){

    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()
}

别忘了在 application(_:didFinishLaunchingWithOptions:)

中使用你的 API_KEY
GMSServices.provideAPIKey("YOUR_API_KEY") 

如果您使用地方信息 API:

GMSPlacesClient.provideAPIKey("YOUR_API_KEY")

参考public documentation

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

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

看看下面这篇讲解关键系统的文章

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

希望对您有所帮助!