-2

How can I play a sound four minutes after my app goes into background mode?

I have tried using NSTimer, but it plays after three minutes instead of four.

func applicationDidEnterBackground(application: UIApplication)
{
    self.timer = NSTimer.scheduledTimerWithTimeInterval(240.0, target: self, selector: "createAVMIDIPlayer", userInfo: nil, repeats: false)
}
func createPlayer() {
    if let soundURL = NSBundle.mainBundle().URLForResource("Text to Speech", withExtension: "m4a") {
        var mySound: SystemSoundID = 0
        AudioServicesCreateSystemSoundID(soundURL, &mySound)
        AudioServicesPlaySystemSound(mySound);
    }
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Sri.av
  • 51
  • 7
  • 2
    Welcome to SO, please take a moment to take the [tour](http://stackoverflow.com/tour) and read about how to ask a [good question](http://stackoverflow.com/help/how-to-ask). You're more likely to get help if you ask a question that's a good fit for this site. – Geoff Atkins Jan 28 '16 at 16:33
  • I'm doing one application. in that app i want play sound after 4 minutes when the app enter to the background – Sri.av Jan 28 '16 at 16:39
  • Edit your question to give a clear description of the problem, the outcome you want to achieve, and what code you have so far. – Geoff Atkins Jan 28 '16 at 16:40
  • 1
    It's simple `NSTimer` do not work in the background. If you app is not playing audio when it goes into the background it will be suspended. You will need to play audio when your app goes in the background (maybe play a silent audio file might work). Since you don't give enough information about when and how we might not be able to help you. – rckoenes Jan 28 '16 at 16:46
  • here is a link to a nice `delay` function, much thanks to @matt for this as I use it frequently ... http://stackoverflow.com/questions/24034544/dispatch-after-gcd-in-swift – MikeG Jan 29 '16 at 01:48
  • this is working only 180 seconds. i need 4 minutes @MikeG – Sri.av Jan 29 '16 at 14:13
  • Here is a library that might be useful to your purpose https://github.com/radex/SwiftyTimer – MikeG Jan 29 '16 at 20:48

1 Answers1

1

In general, iOS apps can't play audio in the background unless they have the correct background modes capabilities set in their plist, and have already started playing audio in the foreground (and haven't stopped).

hotpaw2
  • 70,107
  • 14
  • 90
  • 153