NSTimer in background mode using locationManager d

2019-09-15 03:14发布

I have a function that I want to run in the app background mode and be executed at least every minute to check for wifi connection and to make decisions. I am using locationManager delegate so I can run my NSTimer in the background. However the location manager is consuming a lot of battery power. This app is not for apple release. However I am looking for more efficient settings for location manager so it will not be that power hungry or maybe any other good ideas?. The current settings that I have are ok, but since I enabled automatic pause for location manager, function updates are delayed too much. Before I was using two delegates methods (didEnterRegion and didExitRegion) those were more power-hungry and not accurate. I read tons of available tutorials and checked other related posts on Stack overflow but have not found anything that would help me to solve my problm Here is what I have in my delegate function:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        self.timer = NSTimer.scheduledTimerWithTimeInterval(45, target: self, selector: #selector(self.checkNetworkSSID), userInfo: nil, repeats: true)
        manager.stopMonitoringSignificantLocationChanges()
        manager.stopUpdatingLocation()
    }

Here is what I have in my viewDidLoad and AppDelegate

manager = CLLocationManager()
        manager?.delegate = self
        manager?.requestWhenInUseAuthorization()
        manager?.startUpdatingLocation()
        manager?.desiredAccuracy = kCLLocationAccuracyThreeKilometers
        manager?.pausesLocationUpdatesAutomatically = true
        manager?.activityType = CLActivityType.Fitness

1条回答
混吃等死
2楼-- · 2019-09-15 04:05

For getting Location in Background you need to call this code on your code and make sure add NSLocationAlwaysUsageDescription inside your info.plist

        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
        locationManager.pausesLocationUpdatesAutomatically = false
        locationManager.startMonitoringSignificantLocationChanges()
        if #available(iOS 9.0, *) {
            locationManager.allowsBackgroundLocationUpdates = true
        }
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
查看更多
登录 后发表回答