Skip to content

Commit

Permalink
Update for Swift 2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
ayanonagon committed Nov 26, 2015
1 parent d1d3238 commit a3f2598
Show file tree
Hide file tree
Showing 8 changed files with 67 additions and 46 deletions.
3 changes: 2 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
language: objective-c
osx_image: xcode7.1
before_install:
- gem i cocoapods --no-ri --no-rdoc
- gem i xcpretty --no-ri --no-rdoc
script:
- xcodebuild -workspace Polyglot.xcworkspace -scheme Polyglot -sdk iphonesimulator test | xcpretty -c
- set -o pipefail && xcodebuild -workspace Polyglot.xcworkspace -scheme PolyglotSample -sdk iphonesimulator9.1 test | xcpretty -c
8 changes: 4 additions & 4 deletions Podfile.lock
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
PODS:
- Nocilla (0.9.0)
- Nocilla (0.10.0)
- Polyglot (0.4.0)

DEPENDENCIES:
Expand All @@ -11,7 +11,7 @@ EXTERNAL SOURCES:
:path: .

SPEC CHECKSUMS:
Nocilla: 4d713c56e7357fd0cac0363854d4a58021ad3f41
Polyglot: dddf99978e893f05bd9f3461922de8958f41480b
Nocilla: ae0a2b05f3087b473624ac2b25903695df51246a
Polyglot: 29a83191af1d56f1af28f195ff2cd748814dab47

COCOAPODS: 0.36.0
COCOAPODS: 0.39.0
39 changes: 27 additions & 12 deletions Polyglot/Polyglot.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,22 +88,22 @@ public class Polyglot {


/**
:param: clientId Microsoft Translator client ID.
:param: clientSecret Microsoft Translator client secret.
- parameter clientId: Microsoft Translator client ID.
- parameter clientSecret: Microsoft Translator client secret.
*/
public init(clientId: String, clientSecret: String) {
self.session = Session(clientId: clientId, clientSecret: clientSecret)
self.toLanguage = Language.English
session = Session(clientId: clientId, clientSecret: clientSecret)
toLanguage = Language.English
}

/**
Translates a given piece of text.

:param: text The text to translate.
:param: callback The code to be executed once the translation has completed.
- 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))) {
self.session.getAccessToken { token in
session.getAccessToken { token in
self.fromLanguage = text.language
let toLanguageComponent = "&to=\(self.toLanguage.rawValue.urlEncoded!)"
let fromLanguageComponent = (self.fromLanguage != nil) ? "&from=\(self.fromLanguage!.rawValue.urlEncoded!)" : ""
Expand All @@ -114,14 +114,29 @@ public class Polyglot {
request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {(data, response, error) in
var translation = ""
if let xmlString = NSString(data: data, encoding: NSUTF8StringEncoding) {
translation = xmlString.stringByReplacingOccurrencesOfString("<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">", withString: "")
translation = translation.stringByReplacingOccurrencesOfString("</string>", withString: "")
let translation: String
guard
let data = data,
let xmlString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
else {
translation = ""
return
}

translation = self.translationFromXML(xmlString)

defer {
dispatch_async(dispatch_get_main_queue()) {
callback(translation: translation)
}
}
callback(translation: translation)
}
task.resume()
}
}

private func translationFromXML(XML: String) -> String {
let translation = XML.stringByReplacingOccurrencesOfString("<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">", withString: "")
return translation.stringByReplacingOccurrencesOfString("</string>", withString: "")
}
}
17 changes: 11 additions & 6 deletions Polyglot/Session.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class Session {
}

func getAccessToken(callback: ((token: String) -> (Void))) {
if ((self.accessToken == nil) || self.isExpired) {
if (accessToken == nil || isExpired) {
let url = NSURL(string: "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13")

let request = NSMutableURLRequest(URL: url!)
Expand All @@ -46,9 +46,14 @@ class Session {
request.HTTPBody = bodyString.dataUsingEncoding(NSUTF8StringEncoding)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {(data, response, error) in
let resultsDict: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

let expiresIn = resultsDict["expires_in"] as! NSString
guard
let data = data,
let resultsDict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers),
let expiresIn = resultsDict["expires_in"] as? NSString
else {
callback(token: "")
return
}
self.expirationTime = NSDate(timeIntervalSinceNow: expiresIn.doubleValue)

let token = resultsDict["access_token"] as! String
Expand All @@ -59,11 +64,11 @@ class Session {

task.resume()
} else {
callback(token: self.accessToken!)
callback(token: accessToken!)
}
}

private var isExpired: Bool {
return self.expirationTime?.earlierDate(NSDate()) == self.expirationTime
return expirationTime?.earlierDate(NSDate()) == self.expirationTime
}
}
2 changes: 1 addition & 1 deletion Polyglot/StringExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ extension String {
}

public var language: Language? {
if (count(self) > 0) { // Prevent Index Out of Bounds in NSLinguisticTagger
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) {
Expand Down
6 changes: 4 additions & 2 deletions PolyglotSample.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
objects = {

/* Begin PBXBuildFile section */
6BF86B27E801452077EAF608 /* Pods_PolyglotTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 925AA115444C33786930F106 /* Pods_PolyglotTests.framework */; settings = {ATTRIBUTES = (Weak, ); }; };
76E093B31C869D9803863B0A /* Pods.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DB9A4E55DA20E420F9D1A394 /* Pods.framework */; settings = {ATTRIBUTES = (Weak, ); }; };
6BF86B27E801452077EAF608 /* Pods_PolyglotTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 925AA115444C33786930F106 /* Pods_PolyglotTests.framework */; };
76E093B31C869D9803863B0A /* Pods.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DB9A4E55DA20E420F9D1A394 /* Pods.framework */; };
B60F875D1985F1C200ABB94A /* PolyglotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B60F875C1985F1C200ABB94A /* PolyglotTests.swift */; };
B6156E3F1999D93B002CE52F /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = B67FC7841985F20B0030ABF8 /* Main.storyboard */; };
B6682231199C68AE00DFA909 /* StringExtensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B6682230199C68AE00DFA909 /* StringExtensionTests.swift */; };
Expand Down Expand Up @@ -177,6 +177,8 @@
B60F873C1985F1C200ABB94A /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftMigration = 0710;
LastSwiftUpdateCheck = 0710;
LastUpgradeCheck = 0600;
ORGANIZATIONNAME = "Ayaka Nonaka";
TargetAttributes = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
Expand All @@ -48,15 +48,18 @@
ReferencedContainer = "container:PolyglotSample.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
Expand All @@ -72,10 +75,10 @@
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
Expand Down
27 changes: 11 additions & 16 deletions PolyglotSample/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,28 +36,23 @@ Start translating.

class ViewController: UIViewController {

var translator: Polyglot?
let translator = Polyglot(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET")

@IBOutlet weak var inputTextField: UITextField!
@IBOutlet weak var translationLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
self.translator = Polyglot(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET")
}

@IBAction func didTapTranslateButton(sender: AnyObject) {
guard let text = inputTextField.text else { return }

UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.translator?.translate(self.inputTextField.text) { translation in
dispatch_async(dispatch_get_main_queue(), {
if let language = self.translator?.fromLanguage?.rawValue {
self.translationLabel.text = "Translated from \(language.capitalizedString): \(translation)"
}
else {
self.translationLabel.text = translation
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
translator.translate(text) { translation in
if let language = self.translator.fromLanguage?.rawValue {
self.translationLabel.text = "Translated from \(language.capitalizedString): \(translation)"
}
else {
self.translationLabel.text = translation
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
}
}

0 comments on commit a3f2598

Please sign in to comment.