0
0
iOS Swiftmobile~20 mins

Location services (Core Location) in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Location Tracker
This screen shows the user's current latitude and longitude using Core Location. It updates the location when the user moves.
Target UI
-------------------------
| Location Tracker       |
|-----------------------|
| Latitude: ---.------   |
| Longitude: ---.------  |
|                       |
| [Start Tracking]       |
-------------------------
Request user permission for location access when the app runs
Show current latitude and longitude on screen
Add a button labeled 'Start Tracking' that starts updating location
Update latitude and longitude labels as location changes
Handle permission denied by showing an alert
Starter Code
iOS Swift
import UIKit
import CoreLocation

class LocationTrackerViewController: UIViewController {
    let locationManager = CLLocationManager()

    let latitudeLabel = UILabel()
    let longitudeLabel = UILabel()
    let startButton = UIButton(type: .system)

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        // Setup UI
        latitudeLabel.text = "Latitude: ---.------"
        longitudeLabel.text = "Longitude: ---.------"
        startButton.setTitle("Start Tracking", for: .normal)

        latitudeLabel.translatesAutoresizingMaskIntoConstraints = false
        longitudeLabel.translatesAutoresizingMaskIntoConstraints = false
        startButton.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(latitudeLabel)
        view.addSubview(longitudeLabel)
        view.addSubview(startButton)

        NSLayoutConstraint.activate([
            latitudeLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            latitudeLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 100),

            longitudeLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            longitudeLabel.topAnchor.constraint(equalTo: latitudeLabel.bottomAnchor, constant: 20),

            startButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            startButton.topAnchor.constraint(equalTo: longitudeLabel.bottomAnchor, constant: 40)
        ])

        // TODO: Add your code here
    }
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
iOS Swift
import UIKit
import CoreLocation

class LocationTrackerViewController: UIViewController, CLLocationManagerDelegate {
    let locationManager = CLLocationManager()

    let latitudeLabel = UILabel()
    let longitudeLabel = UILabel()
    let startButton = UIButton(type: .system)

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        latitudeLabel.text = "Latitude: ---.------"
        longitudeLabel.text = "Longitude: ---.------"
        startButton.setTitle("Start Tracking", for: .normal)

        latitudeLabel.translatesAutoresizingMaskIntoConstraints = false
        longitudeLabel.translatesAutoresizingMaskIntoConstraints = false
        startButton.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(latitudeLabel)
        view.addSubview(longitudeLabel)
        view.addSubview(startButton)

        NSLayoutConstraint.activate([
            latitudeLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            latitudeLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 100),

            longitudeLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            longitudeLabel.topAnchor.constraint(equalTo: latitudeLabel.bottomAnchor, constant: 20),

            startButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            startButton.topAnchor.constraint(equalTo: longitudeLabel.bottomAnchor, constant: 40)
        ])

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest

        startButton.addTarget(self, action: #selector(startTracking), for: .touchUpInside)

        checkLocationAuthorization()
    }

    func checkLocationAuthorization() {
        switch CLLocationManager.authorizationStatus() {
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
        case .restricted, .denied:
            showPermissionDeniedAlert()
        case .authorizedWhenInUse, .authorizedAlways:
            // Permission granted, do nothing yet
            break
        @unknown default:
            break
        }
    }

    @objc func startTracking() {
        if CLLocationManager.locationServicesEnabled() {
            locationManager.startUpdatingLocation()
        } else {
            showPermissionDeniedAlert()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        latitudeLabel.text = String(format: "Latitude: %.6f", location.coordinate.latitude)
        longitudeLabel.text = String(format: "Longitude: %.6f", location.coordinate.longitude)
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        checkLocationAuthorization()
    }

    func showPermissionDeniedAlert() {
        let alert = UIAlertController(title: "Location Permission Denied", message: "Please enable location permissions in Settings to use this feature.", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
}

This app uses Core Location to get the user's current position. We first ask for permission to access location data. If permission is denied, we show an alert to inform the user.

The startButton triggers location updates. When the location changes, the delegate method updates the latitude and longitude labels with the new coordinates.

We use CLLocationManagerDelegate to handle location updates and authorization changes. The UI is simple and centered, showing the coordinates clearly.

Final Result
Completed Screen
-------------------------
| Location Tracker       |
|-----------------------|
| Latitude: 37.774929   |
| Longitude: -122.419416|
|                       |
| [Start Tracking]       |
-------------------------
User taps 'Start Tracking' button
App requests location permission if not granted
If permission granted, latitude and longitude update live as user moves
If permission denied, alert appears explaining how to enable permissions
Stretch Goal
Add a 'Stop Tracking' button that stops location updates and resets labels
💡 Hint
Add another UIButton below the start button. When tapped, call locationManager.stopUpdatingLocation() and reset labels to default text.