Created
November 17, 2017 00:31
-
-
Save jfahrenkrug/ef4c47e868673e0aacf34b0cedd883c7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Analyze the sentiment of a given English sentence. | |
- Parameters: | |
- sentence: The sentence to analyze | |
- completion: The block to be called on the main thread upon completion | |
- score: The sentiment score | |
*/ | |
func analyze(_ sentence: String, completion: @escaping (_ score: Int) -> Void) { | |
// Run this asynchronously in the background | |
DispatchQueue.global(qos: .userInitiated).async { | |
var score = 0 | |
let jsModule = self.context.objectForKeyedSubscript("Sentimentalist") | |
let jsAnalyzer = jsModule?.objectForKeyedSubscript("Analyzer") | |
// In the JSContext global values can be accessed through `objectForKeyedSubscript`. | |
// In Objective-C you can actually write `context[@"analyze"]` but unfortunately that's | |
// not possible in Swift yet. | |
if let result = jsAnalyzer?.objectForKeyedSubscript("analyze").call(withArguments: [sentence]) { | |
score = Int(result.toInt32()) | |
} | |
// Call the completion block on the main thread | |
DispatchQueue.main.async { | |
completion(score) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment