create a class in swift to get the user location with cllocation in swift

To create a class in Swift to get the user location using CLLocation, follow these steps:

  1. Open Xcode and create a new Swift file by going to File > New > File (or press CMD + N).
  2. In the dialog box that appears, select Swift File and click Next.
  3. Name the file LocationManager and click Create.
  4. Open the LocationManager file and add the following code:
main.swift
import Foundation
import CoreLocation

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

    override init() {
        super.init()

        manager.delegate = self
        manager.requestWhenInUseAuthorization()

        // Add any additional setup code here. For example, you may want to set the desired location accuracy:
        // manager.desiredAccuracy = kCLLocationAccuracyBest
    }

    // MARK: - CLLocationManagerDelegate methods

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .authorizedAlways, .authorizedWhenInUse:
            manager.startUpdatingLocation()
        default:
            manager.stopUpdatingLocation()
        }
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        // Handle any errors here.
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // Handle location updates here.
        if let location = locations.last {
            // Do something with the location.
            print("Latitude: \(location.coordinate.latitude), Longitude: \(location.coordinate.longitude)")
        }
    }
}
1291 chars
40 lines
  1. In your app where you want to use the location manager, create an instance of the LocationManager class and use it to get the user's location. For example:
main.swift
let locationManager = LocationManager()

// The location manager will automatically start updating the location when it has the necessary permissions.
151 chars
4 lines

Note: Remember to include the required NSLocationWhenInUseUsageDescription key in your app's Info.plist file to request user authorization to access location services.

gistlibby LogSnag