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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With