User location means getting the current geographic position of the device, i.e.:
Directional information refers to:
👉 Simple idea:
Used to access GPS data:
CLLocationManager → gets location updatesCLLocation → stores coordinatesUsed to:
Direction the device is pointing (in degrees):
import MapKit
import CoreLocation
let locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
class ViewController: UIViewController, CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
let lat = location.coordinate.latitude
let lon = location.coordinate.longitude
print("Latitude: \(lat)")
print("Longitude: \(lon)")
}
}
let coordinate = CLLocationCoordinate2D(latitude: 31.5204, longitude: 74.3587)
let region = MKCoordinateRegion(center: coordinate,
latitudinalMeters: 1000,
longitudinalMeters: 1000)
mapView.setRegion(region, animated: true)
mapView.showsUserLocation = true
locationManager.startUpdatingHeading()
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
let direction = newHeading.magneticHeading
print("Device direction: \(direction)")
}
| Degrees | Direction |
|---|---|
| 0° | North |
| 90° | East |
| 180° | South |
| 270° | West |
GPS Sensor
↓
CLLocationManager
↓
Coordinates (Lat, Long)
↓
MapKit (MKMapView)
↓
Display Location + Direction
showsUserLocation = true for map displayPrivacy - Location When In Use Usage Description
We need your location to show your position on the map.
User location = latitude + longitude
Direction = device heading (compass)
Uses:
Important methods:
didUpdateLocationsdidUpdateHeadingRequires permissions in Info.plist
Used in:
Open this section to load past papers