- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(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
}
我想每隔10分钟将坐标发送到网络服务。这样做但这不起作用。我的应用程序已注册,以便在后台获取位置更新。请建议我需要对此程序进行更改。
答案 0 :(得分:5)
通过使用NSUserDefaults记录上次发送到服务器的日期时间并使用NSTimeInterval比较更新后的位置的日期戳和此值,我做了类似的事情。我使用30秒,但你可以向上调整。这有点黑客但它适用于后台运行等。
- (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];
}
答案 1 :(得分:0)
您需要在位置管理器中停止更新。它将继续调用didUpdateToLocation,除非你在第一次返回后停止它。
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
[manager stopUpdatingLocation];
etc...