записать координаты местоположения / GPS в файл - PullRequest
0 голосов
/ 29 июня 2011

Ну, я знаю, что это может звучать просто, но я буквально искал повсюду и не мог найти прямой ответ на этот вопрос. Я пытаюсь сохранить координаты местоположения в файл каждый раз, когда я получаю обновление - звучит просто .... У меня есть две проблемы: одна с типом данных (кажется, что writeToFile сохраняет только NSData), а другая с добавлением конец файла. Я пытался использовать NSKeyedArchiver, но он написал кучу мусора, и я не мог найти, как добавить в конец файла с ним.

Вот мой код - если бы вы могли помочь, я был бы очень признателен. Спасибо!

....

NSMutableArray *array = [[NSMutableArray alloc] init];
NSNumber *numLat = [NSNumber numberWithFloat:location.coordinate.latitude];
NSNumber *numLong = [NSNumber numberWithFloat:location.coordinate.longitude];


[array addObject:numLat];    
[array addObject:numLong];    

NSFileHandle *file;
file = [NSFileHandle fileHandleForUpdatingAtPath: @"./location.txt"];

if (file == nil)
    NSLog(@"Failed to open file");


[file seekToEndOfFile];

[file writeData: array]; //BTW - this line doesn't work if I replace array with numLat which is an NSNumber - unlike what many people have said in various discussions here

ИЛИ - для сохранения в файл (последние две строки):

NSString *path = @"./location.txt";
[NSKeyedArchiver archiveRootObject:array toFile:path];

1 Ответ

1 голос
/ 30 июня 2011
// Get the path to the Documents (this is where your app saves data)
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsPath = [searchPaths objectAtIndex: 0];
[array writeToFile:[documentsPath stringByAppendingPathComponent:@"location"] atomically:YES];

Чтобы загрузить данные обратно в массив, используйте

NSArray *searchPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsPath = [searchPaths objectAtIndex: 0];
array = [[NSMutableArray alloc] initWithContentsOfFile:[documentsPath stringByAppendingPathComponent:@"location"];
...