Search code examples
iosswifttimerbackground-processsleep-mode

How to prevent the app from going to sleep, in order to integrate a sleep mode for the music


I have a working music App, written in Swift. I wanted to integrate a sleep mode which could pause the music played after, say 10 minutes. I used perform(_ aSelector: Selector, with anArgument: Any?, afterDelay delay: TimeInterval) for this task, it worked fine.

But there's a problem. There's a good chance that the iPhone'll go to sleep before the 10 minutes end, so the pause fonction isn't called, and the music continues to play.

I understand that there are other ways to send an action after 10 minutes (NSTimer, use GCD) but if I understand, none of this solutions will prevent the machine to go to sleep, or wake up the app to perform the task.

Perhaps I could use background mode, but:

  1. My goal isn't really in the problems that this mode is supposed to solve. I don't want to have some time to finish, I just want a little 1/10 of second processor at a certain time.
  2. This option don't guarantee to work for a 10 minutes period.

Is this a way to achieve what I need?


Solution

  • You can do: UIApplication.shared.isIdleTimerDisabled = true, as this is the only way in Swift 3, and you could do UIApplication.sharedApplication().idleTimerDisabled = truein Swift 2 or [UIApplication sharedApplication].idleTimerDisabled = YES; in objective-c