title: Swift iOS Text To Speech not working with "delay" in loop
body: <p>I'm trying to have the iOS text-to-speech synthesizer "say" a list of phrases with a variable delay between the phrases.  For example, I may want to it say "Hello", then wait 5 seconds, then "Is anyone there?", then wait 10 seconds, then say "Hello?"...etc.  </p>
  
  <p>I've made a simple example below that illustrates what I am trying to do.  I know that the speech synthesizer is speaking, additional utterances are added to a queue and spoken in the order they are received.</p>
  
  <p>I've tried many ways to achieve this delay in the loop.  Testing delays with a print statement confirms they are working, but they seem to be interfering with the text-speach-functionality which says the first phrase but waits until the for-loop is done before saying the rest. I thought that any of these types of delays would work as I assume the speech synthesizer is event driven.  </p>
  
  <p>I'd appreciate some help, or at least an insight it to why it isn't working.  Thanks!</p>
  
  <p>Here is the example code: iPhone 6 simulator, Xcode 7.3</p>
  
  <pre><code>import UIKit
  import AVFoundation
  
  class ViewController: UIViewController {
  
      let speechSynthesizer = AVSpeechSynthesizer()
      var phraseArray: [String] = ["One", "Two", "Three", "Four", "Five", "Six", "Seven"]
  
      override func viewDidLoad() {
          super.viewDidLoad()
          for phrase in phraseArray{
              let speechUtterance = AVSpeechUtterance(string: phrase)
              speechSynthesizer.speakUtterance(speechUtterance)
  
              //"delay()" goes here.  It needs to be a variable length delay.
  
          }
      }
  }
  </code></pre>
  
  <p>Here are some of the delay methods that I have tried:</p>
  
  <ol>
  <li><p>Setup the class as a delegate for the speech synthesizer and run a while loop until the synthesizer is finished. </p></li>
  <li><p>Time based delay:  <code>referenceDate = NSDate()  while(NSDate().timeIntervalSinceDate(referenceDate) &lt; 0.5) {}</code></p></li>
  <li><p>I've tried "delay" solutions from stack, like this one:  <a href="https://stackoverflow.com/questions/36917544/swift-delay-in-loop">Swift delay in loop</a></p>
  
  <p><code>func delay(delay:Double, closure:()-&gt;()) {
          dispatch_after(
              dispatch_time(
                  DISPATCH_TIME_NOW,
                  Int64(delay * Double(NSEC_PER_SEC))
              ),
              dispatch_get_main_queue(), closure)
      }</code></p></li>
  <li><p>Sleep()</p></li>
  </ol>