From bed20a8f3cad5143feaca69f0e0311340d47cfd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cihat=20Gu=CC=88ndu=CC=88z?= Date: Mon, 19 Sep 2016 18:51:15 +0200 Subject: [PATCH 1/2] Convert classes to Swift 3 --- Polyglot/Polyglot.swift | 26 ++++++++++++------------ Polyglot/Session.swift | 26 ++++++++++++------------ Polyglot/StringExtension.swift | 8 ++++---- PolyglotTests/StringExtensionTests.swift | 2 +- 4 files changed, 31 insertions(+), 31 deletions(-) diff --git a/Polyglot/Polyglot.swift b/Polyglot/Polyglot.swift index 159f1a1..4ebcd5f 100644 --- a/Polyglot/Polyglot.swift +++ b/Polyglot/Polyglot.swift @@ -117,15 +117,15 @@ public enum Language: String { /** Responsible for translating text. */ -public class Polyglot { +open class Polyglot { let session: Session /// The language to be translated from. It will automatically detect the language if you do not set this. - public var fromLanguage: Language? + open var fromLanguage: Language? /// The language to translate to. - public var toLanguage: Language + open var toLanguage: Language /** @@ -143,7 +143,7 @@ public class Polyglot { - parameter text: The text to translate. - parameter callback: The code to be executed once the translation has completed. */ - public func translate(text: String, callback: ((translation: String) -> (Void))) { + open func translate(_ text: String, callback: @escaping ((_ translation: String) -> (Void))) { session.getAccessToken { token in if self.fromLanguage == nil { self.fromLanguage = text.language @@ -152,15 +152,15 @@ public class Polyglot { let fromLanguageComponent = (self.fromLanguage != nil) ? "&from=\(self.fromLanguage!.rawValue.urlEncoded!)" : "" let urlString = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=\(text.urlEncoded!)\(toLanguageComponent)\(fromLanguageComponent)" - let request = NSMutableURLRequest(URL: NSURL(string: urlString)!) - request.HTTPMethod = "GET" + let request = NSMutableURLRequest(url: URL(string: urlString)!) + request.httpMethod = "GET" request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") - let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {(data, response, error) in + let task = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) in let translation: String guard let data = data, - let xmlString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String + let xmlString = NSString(data: data, encoding: String.Encoding.utf8) as? String else { translation = "" return @@ -169,17 +169,17 @@ public class Polyglot { translation = self.translationFromXML(xmlString) defer { - dispatch_async(dispatch_get_main_queue()) { + DispatchQueue.main.async { callback(translation: translation) } } - } + }) task.resume() } } - private func translationFromXML(XML: String) -> String { - let translation = XML.stringByReplacingOccurrencesOfString("", withString: "") - return translation.stringByReplacingOccurrencesOfString("", withString: "") + fileprivate func translationFromXML(_ XML: String) -> String { + let translation = XML.replacingOccurrences(of: "", with: "") + return translation.replacingOccurrences(of: "", with: "") } } diff --git a/Polyglot/Session.swift b/Polyglot/Session.swift index d54b45a..f831c36 100644 --- a/Polyglot/Session.swift +++ b/Polyglot/Session.swift @@ -28,47 +28,47 @@ class Session { let clientSecret: String var accessToken: String? - var expirationTime: NSDate? + var expirationTime: Date? init(clientId: String, clientSecret: String) { self.clientId = clientId self.clientSecret = clientSecret } - func getAccessToken(callback: ((token: String) -> (Void))) { + func getAccessToken(_ callback: @escaping ((_ token: String) -> (Void))) { if (accessToken == nil || isExpired) { - let url = NSURL(string: "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13") + let url = URL(string: "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13") - let request = NSMutableURLRequest(URL: url!) - request.HTTPMethod = "POST" + let request = NSMutableURLRequest(url: url!) + request.httpMethod = "POST" let bodyString = "client_id=\(clientId.urlEncoded!)&client_secret=\(clientSecret.urlEncoded!)&scope=http://api.microsofttranslator.com&grant_type=client_credentials" - request.HTTPBody = bodyString.dataUsingEncoding(NSUTF8StringEncoding) + request.httpBody = bodyString.data(using: String.Encoding.utf8) - let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {(data, response, error) in + let task = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) in guard let data = data, - let resultsDict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers), + let resultsDict = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers), let expiresIn = resultsDict["expires_in"] as? NSString else { callback(token: "") return } - self.expirationTime = NSDate(timeIntervalSinceNow: expiresIn.doubleValue) + self.expirationTime = Date(timeIntervalSinceNow: expiresIn.doubleValue) let token = resultsDict["access_token"] as! String self.accessToken = token callback(token: token) - } + }) task.resume() } else { - callback(token: accessToken!) + callback(accessToken!) } } - private var isExpired: Bool { - return expirationTime?.earlierDate(NSDate()) == self.expirationTime + fileprivate var isExpired: Bool { + return (expirationTime as NSDate?)?.earlierDate(Date()) == self.expirationTime } } diff --git a/Polyglot/StringExtension.swift b/Polyglot/StringExtension.swift index bfe1830..fbd6424 100644 --- a/Polyglot/StringExtension.swift +++ b/Polyglot/StringExtension.swift @@ -25,16 +25,16 @@ import Foundation extension String { public var urlEncoded: String? { - let urlQueryAllowedCharacterSet: NSMutableCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet - urlQueryAllowedCharacterSet.removeCharactersInString("&=?+") - return self.stringByAddingPercentEncodingWithAllowedCharacters(urlQueryAllowedCharacterSet) + let urlQueryAllowedCharacterSet: NSMutableCharacterSet = (CharacterSet.urlQueryAllowed as NSCharacterSet).mutableCopy() as! NSMutableCharacterSet + urlQueryAllowedCharacterSet.removeCharacters(in: "&=?+") + return self.addingPercentEncoding(withAllowedCharacters: urlQueryAllowedCharacterSet as CharacterSet) } public var language: Language? { if characters.count > 0 { // Prevent Index Out of Bounds in NSLinguisticTagger let tagger = NSLinguisticTagger(tagSchemes: [NSLinguisticTagSchemeLanguage], options: 0) tagger.string = self - if let result = tagger.tagAtIndex(0, scheme: NSLinguisticTagSchemeLanguage, tokenRange: nil, sentenceRange: nil) { + if let result = tagger.tag(at: 0, scheme: NSLinguisticTagSchemeLanguage, tokenRange: nil, sentenceRange: nil) { return Language(rawValue: result) } } diff --git a/PolyglotTests/StringExtensionTests.swift b/PolyglotTests/StringExtensionTests.swift index 3616a46..a77892e 100644 --- a/PolyglotTests/StringExtensionTests.swift +++ b/PolyglotTests/StringExtensionTests.swift @@ -39,7 +39,7 @@ class StringExtensionTests: XCTestCase { XCTAssertNil("".language?.rawValue, "Empty strings should return nil.") } - func AssertEqualOptional(@autoclosure optional: () -> T?, @autoclosure _ expected: () -> T, file: String = __FILE__, line: UInt = __LINE__) { + func AssertEqualOptional(@autoclosure optional: () -> T?, @autoclosure _ expected: () -> T, file: String = #file, line: UInt = #line) { if let nonOptional = optional() { if nonOptional != expected() { self.recordFailureWithDescription("Optional (\(nonOptional)) is not equal to (\(expected()))", inFile: file, atLine: line, expected: true) From c5fef05ffffe14e5d01f24ccf47889becddbb7cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cihat=20Gu=CC=88ndu=CC=88z?= Date: Wed, 21 Sep 2016 23:33:46 +0200 Subject: [PATCH 2/2] Manually update code to Swift 3 and Xcode 8 --- Polyglot/Polyglot.swift | 6 +++--- Polyglot/Session.swift | 12 ++++++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Polyglot/Polyglot.swift b/Polyglot/Polyglot.swift index 4ebcd5f..828d3c5 100644 --- a/Polyglot/Polyglot.swift +++ b/Polyglot/Polyglot.swift @@ -152,7 +152,7 @@ open class Polyglot { let fromLanguageComponent = (self.fromLanguage != nil) ? "&from=\(self.fromLanguage!.rawValue.urlEncoded!)" : "" let urlString = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=\(text.urlEncoded!)\(toLanguageComponent)\(fromLanguageComponent)" - let request = NSMutableURLRequest(url: URL(string: urlString)!) + var request = URLRequest(url: URL(string: urlString)!) request.httpMethod = "GET" request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") @@ -160,7 +160,7 @@ open class Polyglot { let translation: String guard let data = data, - let xmlString = NSString(data: data, encoding: String.Encoding.utf8) as? String + let xmlString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as? String else { translation = "" return @@ -170,7 +170,7 @@ open class Polyglot { defer { DispatchQueue.main.async { - callback(translation: translation) + callback(translation) } } }) diff --git a/Polyglot/Session.swift b/Polyglot/Session.swift index f831c36..01a1fd6 100644 --- a/Polyglot/Session.swift +++ b/Polyglot/Session.swift @@ -39,7 +39,7 @@ class Session { if (accessToken == nil || isExpired) { let url = URL(string: "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13") - let request = NSMutableURLRequest(url: url!) + var request = URLRequest(url: url!) request.httpMethod = "POST" let bodyString = "client_id=\(clientId.urlEncoded!)&client_secret=\(clientSecret.urlEncoded!)&scope=http://api.microsofttranslator.com&grant_type=client_credentials" @@ -48,18 +48,18 @@ class Session { let task = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) in guard let data = data, - let resultsDict = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers), - let expiresIn = resultsDict["expires_in"] as? NSString + let resultsDict = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any], + let expiresIn = resultsDict?["expires_in"] as? NSString else { - callback(token: "") + callback("") return } self.expirationTime = Date(timeIntervalSinceNow: expiresIn.doubleValue) - let token = resultsDict["access_token"] as! String + let token = resultsDict?["access_token"] as! String self.accessToken = token - callback(token: token) + callback(token) }) task.resume()