简体   繁体   English

如何将坐标保存到文本文件?

[英]How can I save coordinates to a text file?

I would like the latitude/longitude coordinates to be saved in a text file called "Location.txt" (this file would first have to be created) in "var/mobile/Documents" folder each time I push the "Get My Location" button, each time overwriting the old coordinates. 我希望每次按“获取我的位置”时,将纬度/经度坐标保存在“ var / mobile / Documents”文件夹中的文本文件“ Location.txt”(首先必须创建此文件)中按钮,每次覆盖旧坐标。 Is this possible? 这可能吗? Could someone please give me example of how this can be done. 有人可以给我举例说明如何做到这一点。 Thanks. 谢谢。

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController {
CLLocationManager *locationManager;
}

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc] init];
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (IBAction)getCurrentLocation:(id)sender {
locationManager.delegate = (id)self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;

[locationManager startUpdatingLocation];
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError: %@", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
                           initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;

if (currentLocation != nil) {
    _LongitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
    _LatitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
}

// Stop Location Manager
[locationManager stopUpdatingLocation];
}

@end

You could just create an NSString that your app knows how to read. 您可以创建一个您的应用程序知道如何读取的NSString。 Eg: 例如:

NSString *newLocString = [NSString stringWithFormat:@"%f,%f",currentLocation.coordinate.longitude, currentLocation.coordinate.latitude];
NSString *path = //File Path.txt
NSError *error = nil;
// Save string and check for error
if (![newLocStrin writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
    NSLog(@"An Error occurred: %@", error.localizedDescription);
}

Then read it like this: 然后像这样阅读:

NSString *path = //File Path.txt
NSError *error = nil;
NSString *location = [NSString stringWithContentsOfFile:path usedEncoding:NSUTF8StringEncoding error:&error];
if (!location) {
    NSLog(@"Error reading location file: %@", error.localizedDescription);
} 
else {
    // Have read the string so now format it back
    NSString *longitude = nil;
    NSString *latitude = nil;
    NSScanner *scanner = [NSScanner scannerWithString:location];
    [scanner scanUpToString:@"," intoString:&longitide];
    latitude = [location stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@,",longitude] withString:@""];
   NSLog(@"Location equals %f,%f", longitude.floatValue, latitude.floatValue);
}

It might be easier to use an NSDictionary and save that either to the NSUserDefaults or as a .plist file: 使用NSDictionary并将其保存到NSUserDefaults或保存为.plist文件可能会更容易:

NSDictionary *dict = @{@"Longitude":@(currentLocation.coordinate.longitude), @"Latitude":@(currentLocation.coordinate.latitude)};

Then to user defaults: 然后为用户默认值:

[[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"Location"];
// To read...
NSDictionary *locDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"Location"];
float longitude = [[locDict objectForKey:@"Longitude"] floatValue];
// e.t.c

To write to a .plist file use NSDictionary's writeToFile: atomically: methods similar to NSString's method above. 要写入.plist文件,请使用NSDictionary的writeToFile: atomically:类似于上述NSString方法的方法。

Hope this is enough to get the job done! 希望这足以完成工作!

EDIT: all of the file writing methods overwrite old versions of the file. 编辑:所有文件写入方法都将覆盖文件的旧版本。

EDIT 2: Saving the plist file in your code: 编辑2:将plist文件保存在您的代码中:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;

if (currentLocation != nil) {
    _LongitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
    _LatitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
    NSDictionary *locDict = @{@"Long":@(currentLocation.coordinate.longitude),@"Lat":@(currentLocation.coordinate.latitude)};
    // Probably want to save the file in the Application Support directory
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"location.plist"];
    if (![locDict writeToFile:path atomically:YES]) {
        NSLog(@"An error occurred.");
    }
    // Or save to NSUserDefaults
    [[NSUserDefaults standardUserDefualts] setObject:locDict forKey:@"Location"];
}

// Stop Location Manager
[locationManager stopUpdatingLocation];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM