微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在swift 3 iOS中实现谷歌翻译api

嗨,我是iOS开发的新手,我正在尝试在我的应用程序中实现谷歌翻译API.我从 GitHub https://github.com/prine/ROGoogleTranslate在线找到了一些示例代码.我下载了示例代码并按照提供的说明从google cloud翻译获取api密钥并将其放在代码中但代码无效,iv查看了GitHub上的注释网站,发现它有
其他开发人员工作.我真的不知道我在代码中做错了什么.

ROGoogleTranslateParams.swift

import Foundation

public struct ROGoogleTranslateParams {

    public init() {

    }

    public init(source:String,target:String,text:String) {
        self.source = source
        self.target = target
        self.text = text
    }

    public var source = "de"
    public var target = "en"
    public var text = "Hallo"
}


/// Offers easier access to the Google Translate API
open class ROGoogleTranslate {

    /// Store here the Google Translate API Key
    public var apiKey = "YOUR_API_KEY"

    ///
    /// Initial constructor
    ///
    public init() {

    }

    ///
    /// Translate a phrase from one language into another
    ///
    /// - parameter params:   ROGoogleTranslate Struct contains all the needed parameters to translate with the Google Translate API
    /// - parameter callback: The translated string will be returned in the callback
    ///
    open func translate(params:ROGoogleTranslateParams,callback:@escaping (_ translatedText:String) -> ()) {

        guard apiKey != "" else {
            print("Warning: You should set the api key before calling the translate method.")
            return
        }

        if let urlEncodedText = params.text.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
            if let url = URL(string: "https://translation.googleapis.com/language/translate/v2?key=\(self.apiKey)&q=\(urlEncodedText)&source=\(params.source)&target=\(params.target)&format=text") {

                let httprequest = URLSession.shared.dataTask(with: url,completionHandler: { (data,response,error) in
                    guard error == nil else {
                        print("Something went wrong: \(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 {
                            // Pyramid of optional json retrieving. I kNow with SwiftyJSON it would be easier,but I didn't want to add an external library
                            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)")
                        }
                    }
                })

                httprequest.resume()
            }
        }
    }
}

ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBOutlet var text:UITextField!
    @IBOutlet var fromLanguage:UITextField!
    @IBOutlet var toLanguage:UITextField!
    @IBOutlet var translation:UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view,typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // dispose of any resources that can be recreated.
    }

    @IBAction func translate(_ sender: UIButton) {



        let translator = ROGoogleTranslate()
        translator.apiKey = "YOUR_API_KEY" // Add your API Key here

        var params = ROGoogleTranslateParams()
        params.source = fromLanguage.text ?? "de"
        params.target = toLanguage.text ?? "en"
        params.text = text.text ?? "Hallo"

        translator.translate(params: params) { (result) in
            dispatchQueue.main.async {
                self.translation.text = "\(result)"
            }
        }
    }
}

这些是使用的类.
按“翻译”按钮后得到的结果如下:
响应[403] – 355个字节

感谢您的帮助.该代码可从提供的URL下载
谢谢

解决方法

我是你上面提到的图书馆的作者:).我猜你得到了403,因为你的Google Api帐户尚未正确激活.谷歌已经改变了翻译api的政策,而且不再免费.所以你可能没有在Api帐户中添加信用卡信息,因此得到403错误

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐