Tutorial: Connecting Core Location to a SwiftUI App

How to connect Apple’s Core Location service to a SwiftUI App

Project Setup

Xcode new project screen, with the iOS App template highlighted.
New project settings in Xcode, with SwiftUI selected as the interface and Swift selected as the language.
Xcode screen when opening a new SwiftUI project from the Xcode app template.

Location Data Manager

What is CLLocationManager?

  • Set up Class containing CLLocationManager
  • Set up delegate objects confirming to CLLocationManagerDelegate protocol (Apple Documentation) that will receive updates from CLLocationManager
  • Set up a @Published variable so that our SwiftUI view will update when the status changes in our Class

Setting Up CLLocationManager In Our App

Add new file screen in Xcode, with Swift file selected
Empty Swift File in Xcode for the LocationDataManager class.
A screenshot showing all the different completion options for locationManager in Xcode

Requesting Authorization of Location Data From User

The info tab showing the Info.plist information for our app.
Adding in the “Privacy — Location When In Use Usage Description” key into the Info.plist file
Adding a string as the value for our “Privacy — Location When In Use Usage Description” key

Requesting the Location Data from Core Data

@Published var authorizationStatus: CLAuthorizationStatus?
case .authorizedWhenInUse:  // Location services are available.authorizationStatus = .authorizedWhenInUselocationManager.requestLocation()break

locationManager(_:didUpdateLocations:) — Apple Documentation

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {// Insert code to handle location updates}

locationManager(_:didFailWithError:) — Apple Documentation

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {print("error: \(error.localizedDescription)")}

Connecting the Location Data to a SwiftUI View

@StateObject var locationDataManager = LocationDataManager()
Text("Latitude: \(locationDataManager.locationManager.location?.coordinate.latitude.description ?? "Error loading")")Text("Longitude: \(locationDataManager.locationManager.location?.coordinate.longitude.description ?? "Error loading")")
3 Screenshots showing the app running on a device. The first screenshot shows the location privacy pop up, the second screenshot shows the “Finding your location” text, and the third screenshot shows the CoreLocation working (but the details have been blurred out for privacy reasons).



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store