Hi i have atask to develop the application with Nstimer and background process.
I have already implement background process with timer. And it is excuting good.but i have problem when i minimize application first time at that time it is not running the background process. after minimizing application 3 to 4 times. After that it is working smoothly. i also display the code of background task and timer as follow.
- (void)applicationDidEnterBackground:(UIApplication *)application {
UIApplication* app = [UIApplication sharedApplication];
NSLog(@"Application enter in background");
[NSTimer scheduledTimerWithTimeInterval:2.0f
target:self
selector:@selector(updateCounter:)
userInfo:nil
repeats:YES];
}
And My updateCounter method is as given follow:
- (void)updateCounter:(NSTimer*)timer {
NSString *id = [[UIDevice currentDevice] uniqueIdentifier];
NSLog(@"uniqueid:%@",id);
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *latitude = [NSString stringWithFormat:@"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:@"%f", coordinate.longitude];
NSLog(@"dLatitude : %@", latitude);
NSLog(@"dLongitude : %@",longitude);
}
Is their any problem related code Please help me to solve it.
NSTimer
are paused when the app is in background state.You'll have to start some background task to do what you want. But even with that, you will be limited to a certain amount of time after the app was put in background.
Real backgrounding behavior is only granted for location tracking, VoIP or Audio apps. Other apps must face limitations: once in background, you are given an amount of time to complete tasks you start with
beginBackgroundTaskWithExpirationHandler:
(backgroundTimeRemaining
).The whole thing is described in iOS Application Programming Guide, Executing Code in the Background, especially here.
Check when your app goes to background mode and when it came into foregroud, calculate this difference and add the elapsed time in your timer so that you get an approx total time. I have also implemented the same and its working pretty well in my end.
First of all: Timers won't work as you expect when your app goes in background. (depends on the availability of the run loop and your timeout)
From what i gather from your code, seems you like to have location update when the app is running in background. For this, you should check the guidelines from here: https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW24