AlmoDev
AlmoDev

Reputation: 969

Stop Updating location from different View Controller

I have implemented a code that starts updating user location then present a different view.

self.manager.startUpdatingLocation(interval: 4) self.present(viewController, animated: true , completion: nil)

then when I tried to stop updating location my app is still printing coordinates.

Is there any code to disable location manager from the whole app? Then if I want to start again I want to use same line of code

Things I tried :

 func stopLocation (){
    DispatchQueue.main.async {
        self.locationManager.stopUpdatingLocation()
        self.manager.stopUpdatingLocation()

    }
}

self.manager.stopUpdatingLocation()

Upvotes: 0

Views: 939

Answers (1)

Duncan C
Duncan C

Reputation: 131491

Your problem is that you're creating a different copy of your manager/location manager for each view controller. You want a single object that both view controllers talk to to control your app's use of the location manager.

This is a good use case for the singleton design pattern. Make your Manager class a singleton, and then use that single instance to manage your location manager status.

The call might look like:

Manager.shared.stopUpdatingLocation()

You should be able to Google `Swift singleton pattern" to learn about it. There are dozens and dozens of code examples online.

Upvotes: 1

Related Questions