Implementing google translation api in swift 3 iOS - ios

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?

Try this "POST" method function not the 'Get' method as you implemented -
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()
}
}

Related

IOS Sign In with apple using swift crashes on iPad only on apple review

My webview app was rejected because I don't have apple sign in, so I implemented it and tested it before submitting, I got rejected again that it crashed on iPad running iOS 13.6.1 on WiFi when clicked on sign in with apple. I have tested in almost with all iPad in emulator but it seems to work very fine. Please can someone help me out, am really new in iOS, can't even understand the error logs they included.
Bellow I have included every related class I used for my apple sign in and also a link to error log report ERROR REPORT 1 and ERROR REPORT 2.
My main view controller
class HomeVC: UIViewController {
func signInWithAppleButtonPressed() {
let provider = ASAuthorizationAppleIDProvider()
let request = provider.createRequest()
request.requestedScopes = [.fullName, .email]
let controller = ASAuthorizationController(authorizationRequests: [request])
controller.presentationContextProvider = self
controller.delegate = self
controller.performRequests()
}
//I call this method on javascript callback from webview
//signInWithAppleButtonPressed()
}
Extension for apple login
extension HomeVC: ASAuthorizationControllerDelegate {
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
guard let credentials = authorization.credential as? ASAuthorizationAppleIDCredential else {return}
var payload: [String: Any] = [:]
if user.apple_payload.count > 0 && user.apple_payload["id"] as! String == credentials.user {
payload = user.apple_payload
}else {
payload = [
"givenName": credentials.fullName?.givenName as Any,
"familyName": credentials.fullName?.familyName as Any,
"email": credentials.email as Any,
"id": credentials.user
]
user.apple_payload = payload
}
if let identifyToken = credentials.identityToken {
if let token = String(bytes: identifyToken, encoding: .utf8) {
user.apple_id = credentials.user
payload["identityToken"] = token
let str = Utils.shared.DictionaryToString(payload: payload)
if !str.isEmpty {
SendToBackEnd(Utils.shared.toBase64(str: str))
}
}
return
}
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
print("Authorization returned an error: \(error.localizedDescription)")
}
}
extension HomeVC: ASAuthorizationControllerPresentationContextProviding {
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
return view.window!
}
}
My Utils Class
class Utils {
static let shared = Utils()
func DictionaryToString(payload: [String: Any]) -> String {
if let jsonData = try? JSONSerialization.data(withJSONObject: payload, options: []) {
if let jsonString = String(data: jsonData, encoding: .utf8) {
return jsonString
}
}
return ""
}
func toBase64(str: String) -> String {
let utf8str = str.data(using: .utf8)
if let base64Encoded = utf8str?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) {
return base64Encoded
}
return ""
}
}
My User Class
class User {
var apple_id: String {
get {
return UserDefaults.standard.string(forKey: "UserAppleIdentification") ?? ""
}
set {
UserDefaults.standard.set(newValue, forKey: "UserAppleIdentification")
UserDefaults.standard.synchronize()
}
}
var apple_payload: [String: Any] {
get {
return (UserDefaults.standard.dictionary(forKey: "UserApplePayloadIdentification") ?? [:]) as [String: Any]
}
set {
UserDefaults.standard.set(newValue, forKey: "UserApplePayloadIdentification")
UserDefaults.standard.synchronize()
}
}
}

Codable for API request

How would I make this same API request through codables?
In my app, this function is repeated in every view that makes API calls.
func getOrders() {
DispatchQueue.main.async {
let spinningHUD = MBProgressHUD.showAdded(to: self.view, animated: true)
spinningHUD.isUserInteractionEnabled = false
let returnAccessToken: String? = UserDefaults.standard.object(forKey: "accessToken") as? String
let access = returnAccessToken!
let headers = [
"postman-token": "dded3e97-77a5-5632-93b7-dec77d26ba99",
"Authorization": "JWT \(access)"
]
let request = NSMutableURLRequest(url: NSURL(string: "https://somelink.com")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error!)
} else {
if let dataNew = data, let responseString = String(data: dataNew, encoding: .utf8) {
print("----- Orders -----")
print(responseString)
print("----------")
let dict = self.convertToDictionary(text: responseString)
print(dict?["results"] as Any)
guard let results = dict?["results"] as? NSArray else { return }
self.responseArray = (results) as! [HomeVCDataSource.JSONDictionary]
DispatchQueue.main.async {
spinningHUD.hide(animated: true)
self.tableView.reloadData()
}
}
}
})
dataTask.resume()
}
}
I would suggest to do the following
Create Base Service as below
import UIKit
import Foundation
enum MethodType: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
}
class BaseService {
var session: URLSession!
// MARK: Rebuilt Methods
func FireGenericRequest<ResponseModel: Codable>(url: String, methodType: MethodType, headers: [String: String]?, completion: #escaping ((ResponseModel?) -> Void)) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
// Request Preparation
guard let serviceUrl = URL(string: url) else {
print("Error Building URL Object")
return
}
var request = URLRequest(url: serviceUrl)
request.httpMethod = methodType.rawValue
// Header Preparation
if let header = headers {
for (key, value) in header {
request.setValue(value, forHTTPHeaderField: key)
}
}
// Firing the request
session = URLSession(configuration: URLSessionConfiguration.default)
session.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
if let data = data {
do {
guard let object = try? JSONDecoder().decode(ResponseModel.self , from: data) else {
print("Error Decoding Response Model Object")
return
}
DispatchQueue.main.async {
completion(object)
}
}
}
}.resume()
}
private func buildGenericParameterFrom<RequestModel: Codable>(model: RequestModel?) -> [String : AnyObject]? {
var object: [String : AnyObject] = [String : AnyObject]()
do {
if let dataFromObject = try? JSONEncoder().encode(model) {
object = try JSONSerialization.jsonObject(with: dataFromObject, options: []) as! [String : AnyObject]
}
} catch (let error) {
print("\nError Encoding Parameter Model Object \n \(error.localizedDescription)\n")
}
return object
}
}
the above class you may reuse it in different scenarios adding request object to it and passing any class you would like as long as you are conforming to Coddle protocol
Create Model Conforming to Coddle protocol
class ExampleModel: Codable {
var commentId : String?
var content : String?
//if your JSON keys are different than your property name
enum CodingKeys: String, CodingKey {
case commentId = "CommentId"
case content = "Content"
}
}
Create Service to the specific model with the endpoint constants subclassing to BaseService as below
class ExampleModelService: BaseService<ExampleModel/* or [ExampleModel]*/> {
func GetExampleModelList(completion: ((ExampleModel?)/* or [ExampleModel]*/ -> Void)?) {
super.FireRequestWithURLSession(url: /* url here */, methodType: /* method type here */, headers: /* headers here */) { (responseModel) in
completion?(responseModel)
}
}
}
Usage
class MyLocationsController: UIViewController {
// MARK: Properties
// better to have in base class for the controller
var exampleModelService: ExampleModelService = ExampleModelService()
// MARK: Life Cycle Methods
override func viewDidLoad() {
super.viewDidLoad()
exampleModelService.GetExampleModelList(completion: { [weak self] (response) in
// model available here
})
}
}
Basically, you need to conform Codable protocol in your model classes, for this you need to implement 2 methods, one for code your model and another for decode your model from JSON
func encode(to encoder: Encoder) throws
required convenience init(from decoder: Decoder) throws
After that you will be able to use JSONDecoder class provided by apple to decode your JSON, and return an array (if were the case) or an object of your model class.
class ExampleModel: Codable {
var commentId : String?
var content : String?
//if your JSON keys are different than your property name
enum CodingKeys: String, CodingKey {
case commentId = "CommentId"
case content = "Content"
}
}
Then using JSONDecoder you can get your model array like this
do {
var arrayOfOrders : [ExampleModel] = try JSONDecoder().decode([ExampleModel].self, from: dataNew)
}
catch {
}
First of all, I can recommend you to use this application -quicktype- for turning json file to class or struct (codable) whatever you want. enter link description here.
After that you can create a generic function to get any kind of codable class and return that as a response.
func taskHandler<T:Codable>(type: T.Type, useCache: Bool, urlRequest: URLRequest, completion: #escaping (Result<T, Error>) -> Void) {
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if let error = error {
print("error : \(error)")
}
if let data = data {
do {
let dataDecoded = try JSONDecoder().decode(T.self, from: data)
completion(.success(dataDecoded))
// if says use cache, let's store response data to cache
if useCache {
if let response = response as? HTTPURLResponse {
self.storeDataToCache(urlResponse: response, urlRequest: urlRequest, data: data)
}
}
} catch let error {
completion(.failure(error))
}
} else {
completion(.failure(SomeError))
}
}
task.resume()
}

need to get the country name from open api

Needs to get country name from below api call :
https://restcountries.eu/rest/v1/all
My code :
var arrRes = []
func getCountry() {
let Url: String = "https://restcountries.eu/rest/v1/all"
Alamofire.request(Url).responseJSON { (responseData) -> Void in
do {
if let datas = responseData.result.value {
let data = (datas as AnyObject).data(using: .utf8)!
let parseData = try JSONSerialization.jsonObject(with: data, options: [])
for country in parseData {
if let name = country["name"] as? String {
print(name)
}
}
}
}
catch let error as NSError {
print(error)
}
}
}
getting error here : 'Any' is not convertible to 'AnyObject' on below line let data = (datas as AnyObject).data(using: .utf8)!..
I need to get only name and append to my array.Any other idea or solution to achieve that ?
Replace do catch block of statement with this.
do {
if let countries = responseData.result.value as? [[String: Any]] {
for country in countries {
if let name = country["name"] as? String {
print(name)
}
}
}
}
catch let error as NSError {
print(error)
}
Try this, its working fine for me.
let urlStr = "https://restcountries.eu/rest/v1/all"
let setFinalURl = urlStr.addingPercentEncoding (withAllowedCharacters: .urlQueryAllowed)!
var request = URLRequest(url: URL(string: setFinalURl)!)
request.httpMethod = HTTPMethod.get.rawValue
Alamofire.request(request).responseJSON
{ (responseObject) -> Void in
if responseObject.result.isSuccess
{
print(responseObject.result.value!)
if "\(String(describing: responseObject.response!.statusCode))" == "200"
{
let result = responseObject.result.value! as AnyObject
let countryNamesArr = result.value(forKey: "name") as! NSArray
print(countryNamesArr)
}
else
{
// handle error
}
}
if responseObject.result.isFailure
{
let error : Error = responseObject.result.error!
print(error.localizedDescription)
}
}
You can try
struct Root: Codable {
let name: String
}
func getCountry() {
let urlStr = "https://restcountries.eu/rest/v1/all"
Alamofire.request(urlStr).responseData { (data) in
do {
guard let data = data.data else { return }
let res = try JSONDecoder().decode([Root].self,from:data)
print(res)
}
catch {
print(error)
}
}
}
Just remove this line
let data = (datas as AnyObject).data(using: .utf8)!
and in optional binding just assign data, since value is of type Data?, from optional binding you get Data
if let data = responseData.result.value
then don't forget to downcast your json to array [String:Any]
...jsonObject(with: data, options: []) as? [[String:Any]]
... then don't forget to unwrap this array or you wouldn't be able to iterate through it in for each loop
Also note that since there is Codable, you should use it instead of JSONSerialization. Then you can decode your json using JSONDecoder to your own model which conforms to protocol Decodable.
As a simple approach, you could implement getCountry() like this:
func getCountry() {
let url: String = "https://restcountries.eu/rest/v1/all"
Alamofire.request(url).responseJSON { response in
if let resultValue = response.result.value, let countryObjects = resultValue as? [[String: Any]] {
let countryNames = countryObjects.compactMap { $0["name"] as? String }
print(countryNames)
}
}
}
At this point, there is no need to use JSONSerialization to get the country names; According to the API response, responseData.result.value is an array of countries (dictionaries), each dictionary has a "name" value, what you should do is to map the response to an array of string. countryNames should contains what are you looking for.
The benefit of using compactMap is to avoid any nil name, so countryNames should be [String] instead of [String?].
However, if you believe that you would need to transform the whole response objects into a custom objects (instead of dictionaries), I would highly recommend to follow the approach of using Decodable.
My code, its working well for me.
Swift 5
public func getCountry(completion: #escaping ([String]) -> ()) {
let url: String = "https://restcountries.eu/rest/v1/all"
AF.request(url).responseJSON { (responseData) -> Void in
do {
guard let data = responseData.data else { return }
let res = try JSONDecoder().decode([CountryName].self,from:data)
completion(self.getCountryName(countryName: res))
}
catch {
print(error)
}
}
}
struct CountryName: Codable {
let name: String
}
private func getCountryName(countryName:[CountryName]) -> [String]{
var country:[String] = []
for index in 0...countryName.count - 1{
country.append(countryName[index].name)
}
return country
}

MC Reading from private effective user settings

this is the view controller when I press the button this error appears
this the class that I create instance from it
after creating that instance the error appears
MC Reading from private effective user settings.
import UIKit
class authentication: NSObject {
func runCode(password: String,email: String,name: String, completionHandler:#escaping (Bool) ->()){
struct f {
static var flag = false
}
let Points : Int = 0
let passwardV : String = password
let emailV : String = email
let nameV : String = name
// connect data base
var request = URLRequest(url: URL(string: "https://www./////.com/API/register.php")!)
// POST method
request.httpMethod = "POST"
// post senteace
let postString = "Password="+passwardV+"&Email="+emailV+"&Name="+nameV
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
// check for fundamental networking error
print("error=\(error)")
return
}
//parsing the response
do {
//converting resonse to NSDictionary and get JSON result
let myJSON = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
// receving json result
print(myJSON!)
if(myJSON!["error"] as! Bool == true){
print("alert")
f.flag = false
}
else {
print(myJSON!)
// save enformation in user's divice
let defaults = UserDefaults.standard
defaults.set(nameV, forKey:"Name")
defaults.set(emailV, forKey:"Email")
defaults.set(Points, forKey:"Point")
defaults.synchronize()
//self.shouldPerformSegue(withIdentifier: "TOHomeCustomerVC", sender: self)
f.flag = true
}
} catch let error as NSError {
print(error)
}
}
completionHandler(f.flag)
task.resume()
}
}

How to loop through JSON object and view it as string - Swift

I just started coding in swift and I am at the point that I can get a single value out of the JSON but I can't seem to get all the values out of it by looping trough the array.
so my question is how do I get all the values out and view it as float or string.
here is my code:
let url = URL(string: "http://api.fixer.io/latest")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil
{
print ("ERROR")
}
else
{
if let content = data
{
do
{
//Array
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
//print(myJson)
for items in myJson [AnyObject] {
print(items)
}
//here is the single value part, it looks for the rates then it puts it in label.
if let rates = myJson["rates"] as? NSDictionary{
if let currency = rates["AUD"]{
print(currency);
self.label.text=String(describing: currency)
}
}
}
catch
{
}
}
}
}
task.resume()
Try this code:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.getJson()
}
func getJson(){
let url = URL(string: "http://api.fixer.io/latest")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil
{
print ("ERROR")
}
else
{
if let content = data
{
do
{
//Dic
guard let myJson:[String:Any] = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any] else {return}
//print(myJson)
for items in myJson {
print(items)
}
//here is the single value part, it looks for the rates then it puts it in label.
if let rates = myJson["rates"] as? NSDictionary{
if let currency = rates["AUD"]{
print(currency);
// self.label.text=String(describing: currency)
}
}
}
catch
{
}
}
}
}
task.resume()
}
}
And the result in the console is like below:
The myJson is the dictionary what you want.
I strongly recommend that you use SwiftyJSON to deal with JSON. It's extremely easy to learn and use.
first, you should install SwiftyJSON via CocoaPods (or any other way you like). then you can code it simply like below:
let url = URL(string: "http://api.fixer.io/latest")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil
{
print ("ERROR")
}
else
{
if let content = data
{
// Initialization
let myJson = JSON(data: content)
// Getting a string using a path to the element
self.label.text = myJson["rates"]["AUD"].stringValue
// Loop test
for (key,value):(String, JSON) in myJson["rates"] {
print("key is :\(key), Value:\(value.floatValue)")
}
}
}
}
task.resume()
try this out:
if let currency = rates["AUD"] as? NSDictionary{
for(key,value) in currency {
// the key will be your currency format and value would be your currency value
}
}

Resources