UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to read the user’s location while your app is in the background

Swift version: 5.6

Paul Hudson    @twostraws   

iOS has had the ability to track locations in the background for some time, but the permission system changed in iOS 8 then again in iOS 11 as Apple has tried to stop unscrupulous apps abusing private information.

Reading the user’s location in the background takes a few steps. First, open your Info.plist file, add key called “Privacy - Location Always and When In Use Usage Description” and "Privacy - Location When In Use Usage Description”, then give both of them whatever text you want to show to users when you ask for their location. They are both required, because iOS always allows user to restrict location access to when your app is in use.

Now open whichever controller you want to use to look for the user’s location, and add this import:

import CoreLocation

You need to tell Swift that your class conforms to the CLLocationManagerDelegate protocol so that you can start to receive location updates.

Location tracking is done using the CLLocationManager class, which is also responsible for requesting location permission from users. You need to create a property for this in your class so that you can store the active location manager, so add this:

var locationManager: CLLocationManager?

If you're using a view controller, you'll probably want to initialize this property in viewDidLoad(), like this:

override func viewDidLoad() {
    super.viewDidLoad()

    locationManager = CLLocationManager()
    locationManager?.delegate = self
    locationManager?.requestAlwaysAuthorization()
}

Once you request permission to use your user's location, they'll see an alert with the message you wrote earlier. When they make a choice you'll get a delegate callback called didChangeAuthorization, at which point you can check whether they are authorized you or not:

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    if status == .authorizedAlways {
        // you're good to go!
    }
}

If you’re able to fall back to using location only when your app is in use, you should add a second check to the code above just in case the user didn’t select the option you wanted.

The final step is to tell Xcode that we want location updates to continue being delivered while the app is in the background. Select your project using the project navigator, then find your app’s target and choose the Capabilities tab. You need to enable Background Modes, then check the box marked “Location updates”.

That’s all the code done now, so you can go ahead and implement the didUpdateLocations method and wait for it to be called. Something like this ought to get you started:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last {
        print("New location is \(location)")
    }
}

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 11.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.8/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.