Send Data Every 10 minutes
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions开发者_如何学C:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
locmanager = [[CLLocationManager alloc] init];
[locmanager setDelegate:self];
[locmanager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
//[locmanager setDistanceFilter:10];
updateTimer = [NSTimer timerWithTimeInterval:600 target:self selector:@selector(startUpdating) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:updateTimer forMode:NSDefaultRunLoopMode];
[window makeKeyAndVisible];
return YES;
}
-(void)startUpdating
{
[locmanager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if (newLocation.horizontalAccuracy < 0) return;
CLLocationCoordinate2D loc = [newLocation coordinate];
currentdate=[[NSDate date]timeIntervalSince1970];
latitude = [NSString stringWithFormat: @"%f", loc.latitude];
longitude= [NSString stringWithFormat: @"%f", loc.longitude];
//Call to webservice to send data
}
I want to send coordinates to web service every 10 minutes.Tried doing this but this is not working.My application is registered to get location updates in background.Please suggest me changes that need to be done to this program.
I've done something similar to this by using NSUserDefaults to record the datetime it last sent to the server and using NSTimeInterval to compare between the updated location's datestamp and this value. I am using 30s but you can adjust upwards. It's a bit of hack but it works with background running etc.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
}
updatedLocation = [newLocation retain];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSDate *myDate = (NSDate *)[prefs objectForKey:@"myDateKey"];
NSDate *lastDate = (NSDate *)newLocation.timestamp;
NSTimeInterval theDiff = [lastDate timeIntervalSinceDate:myDate];
if (theDiff > 30.0f || myDate == nil){
//do your webservices stuff here
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:lastDate forKey:@"myDateKey"];
[prefs synchronize];
}
You need to stop updating in your location manager. It will keep calling didUpdateToLocation unless you stop it after it returns the first time.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
[manager stopUpdatingLocation];
etc...
精彩评论