Reputation: 3079
I have a timer which shows the NSTime of a user's work out. Location manager and that timer stops updating when my app goes to background mode. How can i make them updating when my app is in background mode?
I have a view called RunViewController which has start button. When user clicks that button, timer and location manager starts. Code is:
-(void)startRun{
timeSec = 0;
timeMin = 0;
timeHour = 0;
NSString* timeNow = [NSString stringWithFormat:@"%02d:%02d:%02d",timeHour , timeMin, timeSec];
//Display on your label
lblTime.text = timeNow;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
self.locManager = [[CLLocationManager alloc] init];
locManager.delegate = self;
locManager.desiredAccuracy = kCLLocationAccuracyBest; //kCLLocationAccuracyBest
[locManager setDistanceFilter:3]; //kCLDistanceFilterNone
[locManager startUpdatingLocation];
locationManagerStartDate = [[NSDate date] retain];
}
In - (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
simply draws a line on map from old location to new location and save that location in an array.
Thanks in advance.
Upvotes: 2
Views: 2222
Reputation: 1480
Found a solution to implement this with the help of the Apple Developer Forums. I did the following:
Specify location background mode
Use an NSTimer in the background by using
UIApplication:beginBackgroundTaskWithExpirationHandler: In case n is
smaller than UIApplication:backgroundTimeRemaining it does works just fine, in case n is larger, the location manager should be enabled (and disabled) again before there is no time remaining to avoid the background task being killed. This does work since location is one of the three allowed types of background execution.
Note: Did loose some time by testing this in the simulator where it doesn't work, works fine on my phone.
Here is the reference for the same.
Upvotes: 1
Reputation: 2358
Try this..
-(void)viewDidLoad
{
UIDevice* device = [UIDevice currentDevice];
BOOL backgroundSupported = NO;
if ([device respondsToSelector:@selector(isMultitaskingSupported)])
backgroundSupported = device.multitaskingSupported;
NSLog(backgroundSupported ? @"Yes" : @"No");
counterTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
//called after 10min of your app in background
NSLog(@"10 minutes finished.");
}];
theTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(selectorForUpdatingLocation) userInfo:nil repeats:YES];
}
Upvotes: 0