Hallo, ich bin neu in iOS-Entwicklung und ich versuche Google Übersetzung API in meiner App zu implementieren. Ich habe einen Beispielcode online von GitHub https://github.com/prine/ROGoogleTranslate gefunden. Ich lud den Beispielcode herunter und befolgte die Anweisungen, indem ich einen API-Schlüssel von Google Cloud Translate erhalte und ihn innerhalb des Codes platziere, aber der Code funktioniert nicht, iv schaute auf die Kommentare auf der GitHub Seite und stellte fest, dass für andere funktioniert Entwickler. Ich weiß wirklich nicht, was ich im Code falsch mache.Umsetzung von Google Übersetzung API in Swift 3 iOS
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)"
}
}
}
}
Dies sind Klassen verwendet werden. Das Ergebnis, das ich erhalte, wenn ich die Schaltfläche 'translate' drücke, lautet wie folgt: Antwort [403] - 355 Bytes
Ihre Hilfe ist willkommen. Der Code ist zum Download von der URL zur Verfügung gestellt Vielen Dank
Veröffentlichen Sie nicht Ihre API-Schlüssel! – CodeBender
Gibt es einen anderen Grund für einen Fehler 403? Meine Anmeldedaten scheinen in Ordnung zu sein, und ich habe meine Bankdaten eingegeben. –