TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Best approach to share changes between classes

Forums > Swift

Hi!,

Background I have a view (HomeView) where I want to show in a List only the elements that are nearby user location. On the other hand, I have another class to manage the location authorization and the location request (LocationManager). Finally, at HomeView, I create an instance of LocationManager class so the system requests location authorization to the user and perform the location request.

In your opinion, what would be the best approach from HomeView ViewModel class to be aware when the location data is ready in order to start collecting the List elements? Should I use the observer pattern? Is there an easier way?

LocationManager class:

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

    override init() {
        super.init()
        locationManager.delegate = self
        locationManager.distanceFilter = 10000
        locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
        locationManager.activityType = .other
    }

    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        switch manager.authorizationStatus {
        case .notDetermined:
            manager.requestWhenInUseAuthorization()
        case .restricted, .denied:
            ....
            break
        case .authorizedWhenInUse:
            manager.requestLocation()
            break
        default:
            break
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("Location: \(locations.first)")
        // How HomeView should be informed at this point that the location data is ready? <---------------
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Failed \(error)")
    }
}

Thanks!

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.