skip to Main Content

I am using the following observable object to track the users location:

import Foundation
import MapKit

class LocationManager: NSObject, ObservableObject {
    private let locationManager = CLLocationManager()
    @Published var location: CLLocation? = nil
    
    override init() {
        super.init()
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.distanceFilter = kCLDistanceFilterNone
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
    }
    
    func locationServicesEnabled() -> Bool {
        return self.locationManager.locationServicesEnabled()
    }
}

extension LocationManager: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        
        guard let location = locations.last else {
            return
        }
        
        self.location = location
    }
}

However, when I try to compile I get an error next to the return self.locationManager.locationServicesEnabled() statement. The compiler says: Static member 'locationServicesEnabled' cannot be used on instance of type 'CLLocationManager', Replace 'self.locationManager' with 'CLLocationManager'. I do not understand this error because self.locationManager is an instance of CLLocationManager. Please help.

2

Answers


  1. Static means that locationServicesEnabled is a member of the class, not of the object. Use the classname CLLocationManager as suggested.

    Seems like the API has changed, earlier it was an instance method, now it is a class method:

    https://developer.apple.com/documentation/corelocation/cllocationmanager/1620566-locationservicesenabled

    Login or Signup to reply.
  2. static func configureLocationManager(manager: CLLocationManager, delegate: CLLocationManagerDelegate?) {

        manager.allowsBackgroundLocationUpdates = true
        manager.delegate = delegate
        manager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
        
        switch manager.authorizationStatus {
        case .authorizedAlways, .authorizedWhenInUse:
            if CLLocationManager.locationServicesEnabled() {
                manager.requestLocation()
            }
        default:
            manager.requestWhenInUseAuthorization()
        }
    }
    

    Here a piece of code that configured location manager and checks whether the app was allowed by user to use location services.

    Here is more code that could be useful. This is a file that I created to implement the delegate methods.
    https://github.com/aibo-cora/Safe-Bavaria/blob/main/Safe%20Bavaria/View%20Model%20-%20Utility/Find.User.Location.swift

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search