If all you want to store is just the coordinates, then I think NSUserDefaults
would be the easiest solution to implement. There are a few different approaches that would work, here's one that stores all of the coordinates as a string separated by ;
for pairs of coordinates and ,
between longitude and lattitude.
- (void)saveCoordinate:(CLLocationCoordinate2D)coordinate {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *previousCoordinatesString = [defaults objectForKey:@"previousCoordinates"];
NSString *newCoordinatesString;
// check to see if the string has ever been saved for that key
if (previousCoordinatesString) {
newCoordinatesString = [NSString stringWithFormat:@"%@;%f,%f", previousCoordinatesString, coordinate.latitude, coordinate.longitude];
}
else {
newCoordinatesString = [NSString stringWithFormat:@"%f,%f", coordinate.latitude, coordinate.longitude];
}
[defaults setObject:newCoordinatesString forKey:@"previousCoordinates"];
}
To fetch the coordinates that have been saved, fetch the string from NSUserDefaults
and then parse out each coordinate pair. If there's nothing in user defaults then return NO
. Once each coordinate has been parsed, send it to the server. If the device is offline then save the string for later.
- (BOOL)fetchCoordinates {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *previousCoordinatesString = [defaults objectForKey:@"previousCoordinates"];
// check to make sure the string exists
if (!previousCoordinatesString) return NO;
NSArray *coordinateStringsArray = [previousCoordinatesString componentsSeparatedByString:@";"];
NSMutableString *coordinatesToSave = [[NSMutableString alloc] init];
for (NSString *coordinateString in coordinateStringsArray) {
NSArray *coordinatesArray = [coordinateString componentsSeparatedByString:@","];
if (coordinatesArray.count > 1) {
float lattitude = [[coordinatesArray objectAtIndex:0] floatValue];
float longitude = [[coordinatesArray objectAtIndex:1] floatValue];
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(lattitude, longitude);
if (![self sendCoordinatesToServer:coordinate]) {
[coordinatesToSave appendFormat:@";%f,%f", lattitude, longitude];
}
}
}
if (coordinatesToSave.length > 0) {
[defaults setObject:coordinatesToSave forKey:@"previousCoordinates"];
return YES;
}
return NO;
}
- (BOOL)sendCoordinatesToServer:(CLLocationCoordinate2D)coordinate {
if (/*check for network connection*/) {
// send to server
return YES;
}
return NO;
}
The reason for breaking apart each coordinate and attempting to send it separately is so that it can be processed and adapted to your specific needs, but if an entire set of coordinates could be sent as a string at once then that would be a much better option from a mobile perspective.