我正在使用RoGoogleTranslate,也正在使用帐单帐户Google翻译API密钥,但仍然无法正常工作我是从github下载演示

最佳答案

试试这个“ 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()
        }
}

关于swift - 我有Google Cloud Translation API key ,但仍然显示给我响应[403]-355字节,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49001486/

10-14 23:19