Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CLLocationManagerDelegate Singleton

Tags:

ios

swift

I'm trying to create a CLLocationManager Singleton with this interface only Location.start() on ViewController but I don't see any location updates with this structure.
I am using print(mostRecentLocation) to detect a location update.
How can I fix this?

Here is my code in Location.swift:

import CoreLocation

class Location: NSObject, CLLocationManagerDelegate {
    private static var locationManager: CLLocationManager = {
        var manager = CLLocationManager()
        manager.desiredAccuracy = kCLLocationAccuracyBest
        return manager
    }()

    static func start() {
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let mostRecentLocation = locations.last else {
          return
        }

        print(mostRecentLocation)
    }
}

And on ViewController.swift

override func viewDidLoad() {
    super.viewDidLoad()
    Location.start()
}

I see this https://github.com/igroomgrim/CLLocationManager-Singleton-in-Swift
and this https://github.com/irfanlone/CLLocationManager-Singleton-Swift
but I don't like the interface.

like image 917
Amelie Huang Avatar asked Dec 11 '22 08:12

Amelie Huang


1 Answers

Somewhere you have to set the delegate of the location manager.

Anyway a singleton is supposed to be a (shared) instance of a class so I recommend something like this

class Radar: NSObject, CLLocationManagerDelegate {

    static let shared = Radar()

    let locationManager : CLLocationManager

    override init() {
        locationManager = CLLocationManager()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        super.init()
        locationManager.delegate = self
    }

    func start() {
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let mostRecentLocation = locations.last else {
            return
        }

        print(mostRecentLocation)
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
        locationManager.stopUpdatingLocation()
    }
}

And call it

Radar.shared.start()

To get your desired syntax use a class wrapper with a class method

class Location {

    static func start() {
        Radar.shared.start()
    }
}

then you can write

Location.start()
like image 178
vadian Avatar answered Dec 27 '22 21:12

vadian