Search code examples
iostimernstimeribeaconbackground-task

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?.invalidate()
            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.


Solution

  • 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 (update: also works in iOS 10):

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

    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. To be aware, the battery usage may be costly.