Xcode: How to capture user location in Swift?

,

I know what immediately comes to your mind. I know how to capture user location in Swift, that is with MapKit? Right?

Actually, no. MapKit is a resource to work with “Maps” as the name suggests. Location is not necessarily linked to, combined with, bound to Maps in general.

User location is nothing other that a pair of GPS coordinates: latitude and longitude. Once you capture this information, meaning the exact or approximate location of the user, it depends on the final goal of your iOS app to decide what to do with it. You may simply log it, you may calculate the speed, or just display it on the screen. You get the idea, capturing the coordinates is one matter, displaying them on a map is another.

So, going back to our topic, how to capture user location in Swift. This can be achieve by using “CoreLocation” services. Start with the expression “import CoreLocation” right below the usual “import UIKit”.

Here is an example code to examine:

import CoreLocation

class LocationManager: NSObject, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()

override init() {
    super.init()
    locationManager.delegate = self
}

func requestLocation() {
    locationManager.requestWhenInUseAuthorization()
    locationManager.requestLocation()
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let location = locations.last else {
        return
    }
    // Handle the captured location
    print("Latitude: \(location.coordinate.latitude), Longitude: \(location.coordinate.longitude)")
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("Location error: \(error.localizedDescription)")
}
}
let locationManager = LocationManager()
locationManager.requestLocation()

As you may see, in the above example, there is no “map” involved. This code will

  1. Ask for user’s consent to access location information
  2. Read the latest location captured from device
  3. Print the coordinates
  4. Throw error if unable to access location information

You may also user locations[0] instead of “locations.last”, they will give the latest reading of the location information from user’s iOS device. In order to test this, remember to set a “custom location” to your iOS Simulator in Xcode. Otherwise, Xcode will set the default to Apple’s headquarters.

Hope this was helpful!