Gold Challenge (simple way - Chapter 26)


#1

import Cocoa

class ViewController: NSViewController, NSSpeechSynthesizerDelegate {

let speechSynthesizer = NSSpeechSynthesizer()

@IBOutlet var progressIndicator: NSProgressIndicator // my add for the Gold Challenge
@IBOutlet var textView: NSTextView!
@IBOutlet var speakButton: NSButton!                                                   
@IBOutlet var stopButton: NSButton!                                                   

var timer: NSTimer?                                  // my add for the Gold Challenge

var contents: String? {
    get {
        return textView.string
    }
    set {
        textView.string = newValue
    }
}

override func viewDidLoad() {                      
    super.viewDidLoad()
    stopButton.enabled = false                                                        
    speechSynthesizer.delegate = self                                      
    progressIndicator.displayedWhenStopped = false   // my add for the Gold Challenge
}

@IBAction func speakButtonClicked(sender: NSButton) {
    speakButton.enabled = false                                                        
    stopButton.enabled = true                                                         
    progressIndicator.displayedWhenStopped = true    // my add for the Gold Challenge
    
    let interval = Double(contents!.characters.count) / 3600//my add for the G. Chal. 
   
    // my add for the Gold Challenge:
    timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: #selector(ViewController.updateProgress), userInfo: nil, repeats: true)
    if let contents = textView.string where !contents.isEmpty {
        speechSynthesizer.startSpeakingString(contents)
    }
    else {
        speechSynthesizer.startSpeakingString("The document is empty")
    }
}

func updateProgress() {                             // my add for the Gold Challenge
    self.progressIndicator.incrementBy(0.40)
}

@IBAction func stopButtonClicked(sender: NSButton) {
    speechSynthesizer.stopSpeaking()
}

func speechSynthesizer(sender: NSSpeechSynthesizer, didFinishSpeaking finishedSpeaking: Bool) { 
    stopButton.enabled = false                                                         
    speakButton.enabled = true                                                         
    
    progressIndicator.displayedWhenStopped = false  // my add for the Gold Challenge
    timer?.invalidate()                             // my add for the Gold Challenge
    progressIndicator.doubleValue = 0.0             // my add for the Gold Challenge
}

}