toing_toing
toing_toing

Reputation: 2442

didUpdateLocations not getting called swift 3

I am developing a screen that will need to update location every 10 minutes using a timer. Other than that It only needs to update location at first load and when the view appears to the user again. It should stop monitoring once the the user goes to another view.

I have a code that is supposed to do this, but the issue is that the didUpdateLocations method is not called at any point. Also the map does not show the current location (I use simulated locations).

I have correctly set up the permissions and the app worked fine when it was setup to just show the location. I need to do this to reduce battery consumption.

Here is my related code:

In viewDidLoad:

if #available(iOS 8.0, *) {
            self.locationManager.requestAlwaysAuthorization()
        }
        self.locationManager.allowsBackgroundLocationUpdates = true
        self.locationManager.distanceFilter = 1000
        self.locationManager.activityType = CLActivityType.automotiveNavigation
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.pausesLocationUpdatesAutomatically = false
        self.locationManager.startUpdatingLocation()
self.map.showsUserLocation = true

In viewWillAppear:

self.map.showsUserLocation = true
        self.locationManager.startUpdatingLocation()

In viewWillDisappear:

self.map.showsUserLocation = false
            self.locationManager.stopUpdatingLocation()

In didUpdateLocations: (at last line)

self.locationManager.stopUpdatingLocation()

Timer Function: (this gets called fine)

Timer.scheduledTimer(timeInterval: 600.0, target: self, selector: #selector(HomePageViewController.updateLocationFromTimer), userInfo: nil, repeats: true)

   @objc func updateLocationFromTimer()
    {
        self.locationManager.startUpdatingLocation()
    }

I also tried to catch any error with the following code:

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

but it did not get called.

I would love to know why the location is not being updated and why the map is not showing the location. Please help.

Upvotes: 0

Views: 2584

Answers (2)

edwardmp
edwardmp

Reputation: 6591

I did not work for me either and discovered that the place at which you set the delegate impacts this.

E.g. this did not work:

  var locationManager = CLLocationManager() {
        didSet {
            locationManager.delegate = self
        }
    }

Setting it at a later moment did work as expected. Not sure why to be honest, but maybe this helps someone.

Upvotes: 0

Irshad Ahmad
Irshad Ahmad

Reputation: 1383

Make sure you assign the delegate:

self.locationManager.delegate = self

Upvotes: 2

Related Questions