Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- 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)
- }
- }
- }
Add Comment
Please, Sign In to add comment