forked from liakhandrii/google-translate-swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TranslateQuery.swift
213 lines (177 loc) · 6.85 KB
/
TranslateQuery.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
//
// TranslateQuery.swift
//
// Created by Andrii Liakh on 14.03.2015. Updated by Mike ([email protected]) on 01.03.2016.
//
import Foundation
extension String {
public func urlEncode() -> String {
let encodedURL = CFURLCreateStringByAddingPercentEscapes(
nil,
self as NSString,
nil,
"!@#$%&*'();:=+,/?[]",
CFStringBuiltInEncodings.UTF8.rawValue)
return encodedURL as String
}
}
public class TranslateQuery {
private let translateQuery = "https://www.googleapis.com/language/translate/v2"
private let getLanguagesQuery = "https://www.googleapis.com/language/translate/v2/languages"
private let detectLanguageQuery = "https://www.googleapis.com/language/translate/v2/detect"
private var sourceStr:String
private var sourceLang:String
private var targetLang:String="en"
private var status="error"
private var defaultQuery:String
private var jsonName:String
private var parameters:NSMutableDictionary = NSMutableDictionary()
var languages:Array<Language>;
var queryResult:String
var queryResultMessage:String
init(sourceString:String, optional sourceLanguage:String, optional targetLanguage:String, withKey apiKey:String) {
sourceStr = sourceString
sourceLang=sourceLanguage
if (!targetLanguage.isEmpty) {
targetLang=targetLanguage
}
if (!sourceLanguage.isEmpty) {
sourceLang=sourceLanguage
}
status = ""
queryResult = ""
queryResultMessage = "Nothing done..."
defaultQuery = detectLanguageQuery
jsonName = "detections"
languages=Array<Language>()
addParameter(named: "key", value: apiKey)
}
func translate() -> Bool {
addParameter(named: "target",value: targetLang)
addParameter(named: "q",value: sourceStr.urlEncode())
let availableLangs = languages.filter { $0.targetLanguage == targetLang }
if (availableLangs.isEmpty) {
//discover supported languages for this target language
setType(TranslateQueryType.GET_LANGUAGES)
let arrResults=runQuery()
for result in arrResults {
let lang=Language()
lang.targetLanguage=targetLang
for (key,val) in result as! NSDictionary {
if (key as! String == "language") {
lang.supportedLanguageCode=val as! String
}
if (key as! String == "name") {
lang.supportedLanguageName=val as! String
}
}
languages.append(lang)
}
}
if (sourceLang.isEmpty) {
setType(TranslateQueryType.DETECT)
let arrResults=runQuery()
if (arrResults.count>0)
{
if let result = arrResults.lastObject!.lastObject as? NSDictionary {
sourceLang=result["language"] as! String
queryResultMessage="Detected"
}
}
else
{
queryResultMessage="Сannot determine source language"
return false
}
}
addParameter(named: "source",value: sourceLang)
//here we should have known source and target languages
let thisLang = languages.filter { $0.targetLanguage == targetLang && $0.supportedLanguageCode == sourceLang}
//report with friendlyname of detected language
if (!thisLang.isEmpty) {
queryResultMessage+=" " + thisLang[0].supportedLanguageName
queryResultMessage=queryResultMessage.stringByTrimmingCharactersInSet(
NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
//now let's translate stuff
let array = sourceStr.componentsSeparatedByString("\n")
for translateThis in array {
setType(TranslateQueryType.TRANSLATE)
addParameter(named: "q",value: translateThis.urlEncode())
let arrResults=runQuery()
if (status == "error") {
queryResultMessage=arrResults[0] as! String
return false
}
else {
for result in arrResults {
for (key,val) in (result as? NSDictionary)! {
if (key as! String == "translatedText") {
queryResult+=val as! String + "\n"
}
}
}
}
}
return true
}
private func setType(type:TranslateQueryType) {
switch type{
case TranslateQueryType.TRANSLATE:
defaultQuery = translateQuery
status = ""
jsonName = "translations"
case TranslateQueryType.GET_LANGUAGES:
defaultQuery = getLanguagesQuery
status = ""
jsonName = "languages"
case TranslateQueryType.DETECT:
defaultQuery = detectLanguageQuery
status = ""
jsonName = "detections"
}
}
private func addParameter(named name:String, value val:String) {
parameters.setObject(val, forKey: name)
}
private func runQuery() -> NSArray {
var query:String = "\(defaultQuery)?"
for (parameter, value) in parameters {
query += "&\(parameter)=\(value)"
}
let request = NSMutableURLRequest(URL: NSURL(string: query)!)
request.HTTPMethod = "GET"
request.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "content-type")
var response:NSURLResponse?
do {
let responseData:NSData = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
let jsonResult:NSDictionary = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if (jsonResult.objectForKey("data") != nil){
return (jsonResult.objectForKey("data") as! NSDictionary).objectForKey(jsonName) as! NSArray
}
else if(jsonResult.objectForKey("error") != nil)
{
status="error"
return (jsonResult.objectForKey("error")as! NSDictionary).allValues
}
else
{
return NSArray()
}
}
catch
{
return NSArray()
}
}
}
class Language {
var targetLanguage: String = ""
var supportedLanguageCode = ""
var supportedLanguageName = ""
}
private enum TranslateQueryType:Int {
case TRANSLATE = 1
case GET_LANGUAGES = 2
case DETECT = 3
}