How can I save coordinates to a text file?

Nicoll

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. 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
Rob Sanders

You could just create an NSString that your app knows how to read. E.g:

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 *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.

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:

- (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];
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I save lines from terminal to a text file?

How can I save the output of printf into a text file?

How can I save the os commands outputs in a text file?

How can I save my python output to text file

How can I determine which drive to save a text file on?

How can I save my custom data to a text file?

how i can save inputs from html page to text file

How can i get the points coordinates from text file with using Visual Basic?

In tkinter, how can I save text entered into a text area into an already open text file?

How can I parse an XML file from a URL and save specific tags to a Text file?

bash: how can I read text in file into string, modify it and save it another file?

How can I read a text file from the terminal and save the output to another file in java?

How can I save text files for tkinter

How can I save a dictionary to a text file with the order initially I assigned to it in Python?

How can I save sentences I wrote in the command section to a text file

How can I extract text fragments from PDF with their coordinates in Python?

How Can I Create Variables From Text and Convert Coordinates

How do I save a Save/Load a text file in Red

How can I save cursor to file .cur?

How can I save image jpeg file?

How can I save or share a jsfiddle file?

How can I save these struct to a binary file?

How can I save a list of dictionaries to a file?

How can I save the last command to a file?

How can I save a file to the class path

How can I save an ArrayList<MyObject> to a file?

How can I save input to a file?

How can I save file in QTabwidget?

How can I save text from bash output which starts with a specific word in a file?