0

I have a button in a simple view with on click function :

@IBAction func watchAlert(sender: AnyObject) {
    showAlert()
    for i in 1...2{
    AudioServicesPlaySystemSound (1005);
    sleep(2)
    }

}

func showAlert(){
    var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
    self.presentViewController(alert, animated: true, completion: nil)
    alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: dismissAlert ))

}


func dismissAlert(alertView: UIAlertAction!)
{
    println("User click ok button")
}

Even though I am trying to call showAlert() before playing the audio, I could only see the alert getting displayed only after sound gets played. I want the alert to be present first and then sound should play. Any help is appreciated.

Vamsi Krishna
  • 555
  • 6
  • 16

1 Answers1

3

Take out the sleep command (you must never sleep the main thread - the Watchdog process will kill you dead, and besides, you are wrongly freezing the whole interface). Instead: show the alert, then use delayed performance (as in my delay utility here) to play a sound.

(There are other problems with your code; in particular, you will also need to find a new way to play the sound twice, since you must not use sleep; this, too, can be accomplished using delay - nested.)

Community
  • 1
  • 1
matt
  • 447,615
  • 74
  • 748
  • 977
  • This seems good! But i have a question, How do i go about dismissing the music in such a case of using delay (i.e kill all other further plays of tone). – Vamsi Krishna Apr 03 '15 at 17:08