0
0
iOS Swiftmobile~5 mins

Location services (Core Location) in iOS Swift

Choose your learning style9 modes available
Introduction

Location services help your app know where the user is. This lets your app show maps, find nearby places, or give directions.

You want to show the user's current position on a map.
Your app needs to find nearby restaurants or stores.
You want to track a user's run or walk route.
You want to give directions from the user's location.
Your app needs to update content based on where the user is.
Syntax
iOS Swift
import CoreLocation

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

  override init() {
    super.init()
    manager.delegate = self
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()
  }

  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
      print("User location: \(location.coordinate.latitude), \(location.coordinate.longitude)")
    }
  }
}

Always ask the user for permission before accessing location.

Use requestWhenInUseAuthorization() for location only while app is open.

Examples
Ask permission to get location even when app is in background.
iOS Swift
manager.requestAlwaysAuthorization()
Begin getting location updates continuously.
iOS Swift
manager.startUpdatingLocation()
Handle errors if location cannot be found.
iOS Swift
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
  print("Failed to get location: \(error.localizedDescription)")
}
Sample App

This SwiftUI app shows the user's latitude and longitude on screen. It asks permission and updates location automatically.

iOS Swift
import SwiftUI
import CoreLocation

class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
  private let manager = CLLocationManager()
  @Published var location: CLLocationCoordinate2D?

  override init() {
    super.init()
    manager.delegate = self
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()
  }

  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let loc = locations.first {
      DispatchQueue.main.async {
        self.location = loc.coordinate
      }
    }
  }
}

struct ContentView: View {
  @StateObject var locationManager = LocationManager()

  var body: some View {
    VStack(spacing: 20) {
      if let location = locationManager.location {
        Text("Latitude: \(location.latitude)")
        Text("Longitude: \(location.longitude)")
      } else {
        Text("Getting location...")
      }
    }
    .padding()
  }
}
OutputSuccess
Important Notes

Remember to add NSLocationWhenInUseUsageDescription key in your Info.plist with a message explaining why you need location.

Location updates use battery, so stop updates when you don't need them.

Test location features on a real device or use the simulator's location simulation.

Summary

Location services let your app find where the user is.

Always ask permission before accessing location.

Use CLLocationManager and its delegate to get updates.