Abhinav
Abhinav

Reputation: 38162

Running the code when application is in the background or device is locked

I have a piece of code wherein I make a server call and based on the response I play a sound. Now, this does not work when my application is in background or my devicei is locked.

Is there any way we can execute this piece of code (Server call and response handling) even if app is in background or device is locked?

Upvotes: 1

Views: 334

Answers (1)

Conrad Shultz
Conrad Shultz

Reputation: 8808

There is no general solution, which is by design. (Apple does not want you to have a potentially CPU- and power-intensive process running in the background and degrading user experience.)

There are a few limited-case options available:

  1. You said you want to play a sound. If by this you mean "play music" or some such streaming, there is an audio background task that your application can register to perform. Note that you must actually be streaming audio; Apple rightfully frowns upon apps that try to use this approach to circumvent the general-case prohibition and will reject your App Store submission accordingly.
  2. You can invert your scenario and have the server send a push notification through the Apple Push Notification service. Depending on the user's settings, an alert, badge, or sound can result. This might be the best fit for you if you aren't streaming audio.
  3. If what you are really intending to do is, say, finish an upload or download (and the sound is a completion notification), you can request some additional time to finish that task after the app is nominally backgrounded or the device locked. Use -[UIApplication beginBackgroundTaskWithExpirationHandler:] from within the appropriate UIApplicationDelegate methods to register such a task. Note that you have a limited (but appreciable) amount of time to finish your task, and I don't think you can play media in this mode.

Upvotes: 5

Related Questions