Get User Location Real-Time Swift 5

iOS Swift

You’re going to learn how to get the user’s location in real-time using CoreLocation including getting updates when the app goes into background mode.

I assume that you have Xcode installed already and know how to create a project in Xcode.

STEP #1: Set Up LatLngLabel

Let’s create a UILabel called latLngLabel that displays the latitude and longitude values of the current location.

import UIKit

class ViewController: UIViewController{
   
    private let latLngLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = .systemFill
        label.numberOfLines = 0
        label.textAlignment = .center
        label.font = .systemFont(ofSize: 26)
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()        
        latLngLabel.frame = CGRect(x: 20, y: view.bounds.height / 2 - 50, width: view.bounds.width - 40, height: 100)
        view.addSubview(latLngLabel)
    }
}

The LatLngUILabel is initialized with some properties and assigned a location (x, y) and dimensions (width, height) of it using frame property inside the viewDidLoad()

I could use Auto Layout but I used fixed values to position it on view for simplity sake.

Finally, add them to the view object using addSubView() method and the app view will look like this.

Add Privacy Properties To Info.plist

So, Go to the project navigator → info.plist and hit the + sign at the top right in the key column and choose

  • Privacy – Location Always and When In Use Usage Description, and
  • Privacy – Location When In Use Usage Description

The value of these properties will actually be visible to the user on the permission alert view.

For Example: “You location is shared to the admin for efficient purposes”

Core Location

As you can see, I have imported CoreLocation at the top and declared locationManager which is optional with a type of CLLocationManager inside the class definition.

import UIKit
import CoreLocation

class ViewController: UIViewController{
    private var locationManager:CLLocationManager?
    ...
    
    override func viewDidLoad() {
        super.viewDidLoad()
        ...
        getUserLocation()
    }

   func getUserLocation() {
        locationManager = CLLocationManager()
        locationManager?.requestAlwaysAuthorization()
        locationManager?.startUpdatingLocation()
    }
}

Then, instantiate CLLocationManager inside getUserLocation() function.

The requestAlwaysAuthorization() method is actually showing the permission alert view to the screen.

When the user gives permission by choosing Allow Once, the startUpdatingLocation()method is actually getting the location data from the device GPS.

And you can see the location icon at the status bar has a filled color.

CLLocationManagerDelegate()

To access an actual user location data, we need to use the didUpdateLocations()method which is a part of CLLocationManagerDelegate.

So add the CLLocationManagerDelegate in the class definition.

class ViewController: UIViewController, CLLocationManagerDelegate{
...
}

Then, set delegate property of locationManager to self.

func getUserLocation() {
  ...
  locationManager?.delegate = self
  ...
}

Finally, define the didUpdateLocations()method which will be called every time there is a new location update.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last {
        latLngLabel.text = "Lat : \(location.coordinate.latitude) \nLng : \(location.coordinate.longitude)"
    }
}

The location parameter is an array of CLLocation objects and the latest location data will be available at the last item.

Once the location object is unwrapped, set the latitude and longitude values to the latLngLabel.

Run the app and it actually gets the user’s location only once.

To get location updates frequently, go to the iOS Simulator menu bar at the top choose Debug Location Freeway Drive.

Now, the app should get location updates frequently.

Location Updates in Background Mode

As soon as the app goes into the background mode, the location icon at the status bar goes away after a few seconds indicating the location updates stop working.

There are two steps to enable that functionality.

The first step is to enable Location Updates in the Background Mode.

  • Go the Application target → Sign in & Capabilities Capabilities button on the left Choose Background Modes.
  • Then, enable location updates.

The second step is to let the locationManager know about it by allowing Background Location Updates to true.

func getUserLocation() {
  ...
  locationManager?.allowsBackgroundLocationUpdates = true
  ...
}

Run the application and the user location now gets updated in the background mode as well.

Also, you can see the location icon at the status bar is flashing in the background mode indicated it’s still getting locations updates.