Как получить locationManager startMonitoringSignificantLocationИзменяет точные показания - PullRequest
0 голосов
/ 29 июня 2011

Привет У меня есть требование, где мне нужно обновить местоположение пользователя на сервере, пока приложение работает в фоновом режиме.Я использовал приведенный ниже код, чтобы протестировать его в машине, и обнаружил несколько расхождений в широте и долготе, о которых сообщается, когда - (void) locationManager: (CLLocationManager *) manager didUpdateToLocation: запускается. Координаты находятся далеко отгде я на самом деле нахожусь в тот момент.

Я знаю, что didupdatelocation использует показания вышек сотовой связи, следовательно, не очень точные. Мне было интересно, есть ли в любом случае, я могу запустить [locationManager startUpdatingLocation] когда - (void) locationManager: (CLLocationManager *) didUpdateToLocation :;и затем получите показания, которые являются гораздо более точными.

Пожалуйста, любая помощь или указания будут полезны и высоко ценится.

#import "LocationsAppDelegate.h"
#import "RootViewController.h"


@implementation LocationsAppDelegate

@synthesize window;
@synthesize navigationController;

-(void)initLocationManager {
    if (locationManager == nil) {
        locationManager = [[CLLocationManager alloc] init];
        locationManager.delegate = self;
        locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; // 100 m
       // [locationManager startUpdatingLocation];
        [locationManager startMonitoringSignificantLocationChanges];
    }
}

- (void)saveCurrentData:(NSString *)newData {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *savedData = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:@"kLocationData"]];
    [savedData addObject:newData];
    [defaults setObject:savedData forKey:@"kLocationData"];
    [savedData release];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

    NSDate* eventDate = newLocation.timestamp;

    NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];

    //check if the data is less than 15 sec ago
    if (abs(howRecent) > 15.0)
    {
        NSLog(@"old data latitude %+.6f, longitude %+.6f\n",
        newLocation.coordinate.latitude,newLocation.coordinate.longitude);

    }else{

        [locationManager startUpdatingLocation];

        NSDateFormatter * formatter = [[[NSDateFormatter alloc] init] autorelease];
        [formatter setTimeStyle:NSDateFormatterMediumStyle];
        NSString *locationData = [NSString stringWithFormat:@"%.6f, %.6f, %@",newLocation.coordinate.latitude, newLocation.coordinate.longitude,[formatter stringFromDate:newLocation.timestamp]];

        [self saveCurrentData:locationData];

        [locationManager stopUpdatingLocation]; 
    }    

}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSString *errorData = [NSString stringWithFormat:@"%@",[error localizedDescription]];
    NSLog(@"%@", errorData);
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    if (![CLLocationManager significantLocationChangeMonitoringAvailable]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"Your device won't support the significant location change." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
        return YES;
    }
    [self initLocationManager];
    [self.window addSubview:navigationController.view];
    [self.window makeKeyAndVisible];

    return YES;
}

- (void)dealloc {
    [locationManager release];
    [navigationController release];
    [window release];
    [super dealloc];
}

@end

1 Ответ

0 голосов
/ 29 июня 2011

На свойства startMonitoringSignificantLocationChanges не влияют свойства distanceFilter или desiredAccuracy.

Поэтому, если вы хотите получить более достоверные результаты, наберите startUpdatingLocation и поиграйте с *Свойства 1007 * и desiredAccuracy (kCLLocationAccuracyBestForNavigation, kCLLocationAccuracyBest) наиболее эффективны, но потребляют больше энергии, поэтому поиграйте с ними.

Я не совсем понял поведение вашего кода.Почему вы вызываете startMonitoringSignificantLocationChanges вместо startUpdatingLocation, но вызываете его внутри метода делегата?

...