在swift 3 iOS中实现谷歌翻译API [英] Implementing google translation api in swift 3 iOS

查看:461
本文介绍了在swift 3 iOS中实现谷歌翻译API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我是iOS开发新手,我正尝试在我的应用程序中实现Google翻译API。我从GitHub上找到一些示例代码 https://github.com/prine/ROGoogleTranslate 。我下载了示例代码,并按照从google云翻译中获取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
}


///提供更方便地访问Google翻译API
公开课ROGoogleTranslate {

///在此处存储Google翻译API密钥
public var apiKey =YOUR_API_KEY

///
///初始构造函数
///
public init(){

}

///
///将一个短语从一种语言翻译成另一种语言
///
/// - 参数参数:ROGoogleTranslate Struct包含所有需要用Google Translate API翻译的参数
/// - 参数回调:翻译的字符串将在回调函数中返回
///
open func translate(params:ROGoogleTranslateParams ,callback:@escaping(_ translatedText:String) - > ()){

guard apiKey!=else {
print(警告:您应该在调用translate方法之前设置api键。)
return


如果让urlEncodedText = params.text.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed){
if let url = URL(string:https://translation.googleapis.com/ ?语言/翻译/ v2的键= \(self.apiKey)及q = \(urlEncodedText)及源= \(params.source)及目标= \(params.target)及格式=文本){

让httprequest = URLSession.shared.dataTask(with:url,completionHandler:{(data,response,error)in
guard error == nil else {$ b $如果让httpResponse = response作为HTTPURLResponse {

警卫httpResponse.statusCode == 200 else {

如果让data = data {
print(Response [\(httpResponse.statusCode)] - \(data))
}

return
}

do {
//可选json检索金字塔。我知道用SwiftyJSON它会更容易,但我不想添加外部库
如果让data = data {
如果让json = try JSONSerialization.jsonObject(with:data,options:JSONSerialization .ReadingOptions.mutableContainers)为? NSDictionary {
如果让jsonData = json [data] as? [字符串:任何] {
如果让translations = jsonData [translations] as? [NSDictionary] {
如果让translation = translations.first as? [字符串:任何] {
如果让translationText = translation [translatedText] as? String {
callback(translatedText)
}
}
}
}
}
}
} catch {
打印(序列化失败:\(error.localizedDescription))
}
}
})

httprequest.resume()
}
}
}
}




ViewController.swift




 导入UIKit 

类ViewController:UIViewController {

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

覆盖func viewDidLoad(){
super.viewDidLoad()
//加载视图后通常从一个nib执行任何其他设置。
}

重写func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
//处理任何可以重新创建的资源。

$ b @IBAction func translate(_ sender:UIButton){



翻译器= ROGoogleTranslate()
translator.apiKey =YOUR_API_KEY//在此处添加您的API密钥

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

这些都是使用的类。
当我按'translate'按钮时得到的结果如下:
响应[403] - 355字节

您的帮助表示赞赏。代码可以从提供的网址下载
谢谢 解决方案

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


Hi i am new to iOS development and i am trying to implement google translation API within my app. I found some sample code online from GitHub https://github.com/prine/ROGoogleTranslate. I downloaded the sample code and followed the instructions provided by obtaining an api key from google cloud translate and placing it within the code however the code is not working, iv looked at the comments on the GitHub site and found that it has worked for other developers. I really don't know what i am doing wrong in the code.

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

These are classes are used. The result i get when i press the 'translate' button is the following: Response [403] - 355 bytes

your help is appreciated. The code is available to download from the url provided Thank you

解决方案

I'm the author of the library you mentioned above :). I guess you get the 403 because your Google Api Account is not yet activated correctly. Google has changed the policy of the Translation api and its not free anymore. So you problably didn't add the credit card informations in the Api account and therefor get the 403 error?

这篇关于在swift 3 iOS中实现谷歌翻译API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆