Mateusz Tylman Mateusz Tylman - 4 years ago 137
iOS Question

Count while in background (NSTimer for more than 3 mins)

Is there any way to run NSTimer for more than 3 mins in background?
I have to create simple app that uses

`locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion)`

for scan my beacons. I have run into problem when I needed to check if user is exactly 10 seconds near closest beacon. I created

var timer: NSTimer?
var lastClosestBeacon: CLBeacon? {
didSet {
timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: "showLocalNotification", userInfo: nil, repeats: false)
// NSRunLoop.mainRunLoop().addTimer(timer!, forMode: NSDefaultRunLoopMode)

When closest beacon changes lastClosestBeacon is set and timer is scheduled. It is working in App and for 3 mins when user enters background(locks phone etc.) with help from Scheduled NSTimer when app is in background?
Is there any possibility to check that for more than 3 mins ?

PS. I have already added Background Modes with location updates.

Answer Source

You can do it by following way:

1) First include required background mode keys into your Info.plist

2) Check and add following line of code for adding background working of location manager in iOS 9

if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];

3)Then create a new timer with repeated continuously with every 1 sec.

4)In that timer method add these two line of code.

[self.locationManager stopUpdatingLocation];
[self.locationManager startUpdatingLocation];

This make your app run in background more than 3 mins.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download