iOS应用swift 3中的谷歌翻译rest api错误403
Posted
技术标签:
【中文标题】iOS应用swift 3中的谷歌翻译rest api错误403【英文标题】:Google Translate rest api error 403 in iOS app swift 3 【发布时间】:2017-05-11 17:18:59 【问题描述】:有人可以帮我解决这个问题吗?
我正在 swift 3 中开发一个应用程序,我正在尝试将 google translate api 集成到我的 ios 应用程序中,但其余 api 响应以下错误:
["error":
code = 403;
errors = (
domain = global;
message = "Requests from this ios client application <empty> are blocked.";
reason = forbidden;
);
message = "Requests from this ios client application <empty> are blocked.";
status = "PERMISSION_DENIED";
]
【问题讨论】:
【参考方案1】:您是否关注过: Implementing google translation api in swift 3 iOS?
正如他所说,您必须正确激活您的帐户并注册,因为它似乎不再是免费的 API。
【讨论】:
我已经正确设置了项目。在云开发者控制台上启用了 api。启用计费并支付翻译 api 的费用。但仍然得到错误。这个错误在安卓设备上也很常见。【参考方案2】:我认为这不是免费使用 API 的问题或任何问题,我已通过将“GET”方法 api 调用更改为“POST”方法解决了这个问题,你可以试试这个 -
open func translateTest(params: GoogleAITranslateParams, targetLanguage: String, callback:@escaping (_ translatedText:String) -> ())
guard apiKey != "" else
return
var request = URLRequest(url: URL(string: "https://translation.googleapis.com/language/translate/v2?key=\(self.apiKey)")!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(Bundle.main.bundleIdentifier ?? "", forHTTPHeaderField: "X-Ios-Bundle-Identifier")
let jsonRequest = [
"q": params.text,
"source": "en",
"target": targetLanguage,
"format": "text"
] as [String : Any]
if let jsonData = try? JSONSerialization.data(withJSONObject: jsonRequest, options: .prettyPrinted)
request.httpBody = jsonData
let task: URLSessionDataTask = URLSession.shared.dataTask(with: request) (data, response, error) in
guard error == nil else
print("Something went wrong: \(String(describing: error?.localizedDescription))")
return
if let httpResponse = response as? HTTPURLResponse
guard httpResponse.statusCode == 200 else
if let data = data
print("Response [\(httpResponse.statusCode)] - \(data)")
return
do
if let data = data
if let json = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
if let jsonData = json["data"] as? [String : Any]
if let translations = jsonData["translations"] as? [NSDictionary]
if let translation = translations.first as? [String : Any]
if let translatedText = translation["translatedText"] as? String
callback(translatedText)
catch
print("Serialization failed: \(error.localizedDescription)")
task.resume()
【讨论】:
【参考方案3】:缺少这一行是被阻止的主要原因,因为我限制 API 密钥 到我的iOS Bundle Identifier:
request.addValue(Bundle.main.bundleIdentifier ?? "", forHTTPHeaderField: "X-Ios-Bundle-Identifier")
【讨论】:
以上是关于iOS应用swift 3中的谷歌翻译rest api错误403的主要内容,如果未能解决你的问题,请参考以下文章