Skip to content

Instantly share code, notes, and snippets.

@jfahrenkrug
Created November 17, 2017 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfahrenkrug/ef4c47e868673e0aacf34b0cedd883c7 to your computer and use it in GitHub Desktop.
Save jfahrenkrug/ef4c47e868673e0aacf34b0cedd883c7 to your computer and use it in GitHub Desktop.
/**
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