简体   繁体   中英

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.

确保分配了委托:

self.locationManager.delegate = self

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

Eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM