Background Modes Tutorial: Getting Started

In this tutorial, you’ll create an app that uses audio playback, location updates, critical tasks, and background fetch to learn about the most common background modes. By Chuck Krutsinger .

4 (4) · 3 Reviews

Download materials
Save for later
Share
Update note: Chuck Krutsinger updated this tutorial for Swift 5.5, iOS 15 and Xcode 13. Chris Wagner wrote the original.

Apple started allowing apps to do work in the background in 2010 with the release of iOS 4 and has evolved and improved background modes since then. iOS restricts the use of background operations to improve user experience and extend battery life. Your app can run in the background for specific use cases, including: playing audio, updating location and fetching the latest content from a server.

If your task doesn’t fall into one of the permitted categories, backgrounding may not be for you. You could face one of those dreaded App Store rejections if you try to game the system with background modes that operate beyond the scopes of their purposes. Consider yourself warned!

In this background modes tutorial, you’ll learn about four things your apps can do in the background:

  • Play audio: Allow the app to continue playing audio in the background.
  • Receive location updates: Enable the app to receive location changes in the background.
  • Complete finite-length critical tasks: Enable the app continue to complete a critical task after moving to the background.
  • Background Fetch: Perform background updates on a schedule determined by iOS.

Getting Started

Download the project files at the top or bottom of the tutorial by clicking the Download Materials button. The user interface and core logic are already built.

Before digging in, here’s a quick overview of the basic background modes available in iOS:

  • Audio, AirPlay, and Picture in Picture: Play audio and video while the app is in the background.
  • Location Updates: Continue to receive location updates when in the background.
  • Voice over IP: Send and receive voice over the internet.
  • External accessory communication: Communicate via the lightning port with external accessories.
  • Using Bluetooth LE accessories: Communicate with Bluetooth LE accessories while in the background.
  • Acting as a Bluetooth LE accessory: Allow the app to serve Bluetooth LE information to an accessory.
  • Background fetch: Perform data refreshes.
  • Remote notitifications: Send and receive remote notifications.
  • Background processing: Perform longer critical processes.

You’re going to add four of the above modes to the sample app – audio, location, background processing and background fetches. If you’re only interested in some of these modes, feel free to skip around and just play with the modes that interest you.

Note: For the full effect, you should follow along on a real device. In Simulator, the app might appear to run in the background when you forget a step. Then when you switch to a real device, it may not work at all.

Before you can run the project on a physical device, you must set your development team, as shown here:

Select your development team

Build and run the sample project to get a feel for Sleepless, an app that never rests because it does things in the background. There are four tabs — one to cover each mode:

First look at Sleepless sample app

The first capability you’re going to add is background audio.

Playing Audio

Build and run Sleepless on a physical device. Navigate to the audio tab, play the music, and then put the app in the background by returning to the home screen. The music will stop playing.

Open AudioModel.swift.

The app makes use of AVQueuePlayer to queue up songs and play them in sequence. The model observes the player’s currentItem value to provide updates to the view.

Giving Credit Where Credit Is Due

The starter project includes audio files from incompetech.com, a popular royalty-free music website. You can use the music for free with atttribution. All three songs are by Kevin MacLeod:

Thanks for the wonderful music, Kevin!

Note: Check out Execution States for Apps on Apple’s UIKit documentation to learn more about the active state and others.

Testing Audio in the Background

Why does the music stop when the app enters the background? Well, a crucial piece is missing!

Most background modes won’t work unless you enable specific capabilities that indicate that the app wants to run code in the background. The exception is critical task completion, which any app can perform.

When activated, the audio background mode tells iOS to continue playing audio even though the app is in the background. That’s right — the audio background mode is virtually automatic. You just have to activate it.

Return to Xcode and do the following:

  1. Click the project in the Project navigator.
  2. Select SleeplessApp target.
  3. Select the Signing & Capabilities tab.
  4. Click on the + symbol to add a capability.

Next, double-click Background Modes to add this capability. Expand the Background Modes capability, then check the Audio, AirPlay, and Picture in Picture box to enable background audio.

Add audio background mode to project

Build and run the app on a physical device. Start the music as before, then leave the app. This time the audio will continue. It’s that simple!

SleeplessApp playing music in the background

Next, you’ll use the Location updates background mode to continue to receive location updates even when the app is in the background.

Receiving Location Updates

First, build and run the app. Choose the Location tab and tap Start. Nothing happens yet because you’re missing some important steps. You’ll change that now.

Enabling Location Updates

Open LocationModel.swift. This is the code that provides location data to the LocationView. You’re going to make a simple change to init(). Replace following two lines:

  mgr.requestWhenInUseAuthorization()
  mgr.allowsBackgroundLocationUpdates = false

With:

 mgr.requestAlwaysAuthorization()
 mgr.allowsBackgroundLocationUpdates = true

The first line requests location updates even when the app is not in use. The second requests updates even in the background.

Go back to the Signing & Capabilities screen and check the box for Location updates to let iOS know that your app wants to receive location updates while in the background.

Enable location updates background mode

In addition to checking this box, iOS requires that you set a key in your Info.plist explaining to the user why you need background updates. If you don’t include this, location requests will silently fail.

Open Info.plist and add the keys for Privacy — Location Always and When In Use Usage Description and Privacy — Location When In Use Usage Description. Then type The app will show your location on a map as the value for both keys.

Usage descriptions for location updates

Now, build and run! Switch to the Location tab and tap Start.

When it loads the first time, you’ll see the message that you wrote into your location privacy reason.

Tap Allow while using app and take a walk outside or around your building — try not to get too distracted catching Pokemons.

Permission to track location

Location updates should start to appear. If they don’t, send the app to the background again to trigger the Always prompt for location tracking. You can also use the Settings app to enable always tracking by the Sleepless app in the Privacy ▸ Location Services ▸ Sleepless settings.

If you send the app to the background, you’ll still see location updates occurring in the console.

After a while, you should see something like this:

Location updates as pins on map