I have a Location class that contains a lat/lon as well as an elevation and timestamp:
@interface Location : NSObject <NSCoding> {
double lon;
double lat;
double ele;
NSDate *time;
NSDateFormatter *gpxDateFormatter;
}
I want to be able to serialize an NSMutableArray
containing an arbitrary number of these Location objects into GPX XML format:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<gpx xmlns="http://www.topografix.com/GPX/1/1" creator="" version="1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">
<trk>
<name>ACTIVE LOG173327</name>
<trkseg>
<trkpt lat="52.347223" lon="4.893477">
<ele>-1.514</ele>
<time>2008-02-04T16:33:26Z</time>
</trkpt>
[........]
</trkseg>
</trk>
</gpx>
I'd like to do this using an NSKeyedArchiver, but I don't know if that would be possible and if it would, how to do it. Any ideas?
EDIT For posterity and if it indeed proves too complicated: here's my quick and dirty solution. I extended the NSMutableArray class with this method:
- (NSString *)locationsAsGPX {
NSMutableString *tempGPXString = [NSMutableString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n<gpx xmlns=\"http://www.topografix.com/GPX/1/1\" creator=\"\" version=\"1.1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\n"];
[tempGPXString appendString:@"<trk>\n<name>%@</name>\n<trkseg>\n"];
for (Location *l in self) {
[tempGPXString appendFormat:@"%@",[l asGPXTrackpoint]];
}
[tempGPXString appendString:@"<trkseg>\n<trk>\n<gpx>"];
return tempGPXString;
}
and the asGPXTrackpoint
method in the Location class looks like this:
-(NSString *)asGPXTrackpoint {
if (self.lat==0.0 || self.lon==0.0) {
return [NSString string];
}
NSMutableString *tempTrackpointString = [NSMutableString stringWithFormat:@"<trkpt lat=\""];
[tempTrackpointString appendFormat:@"%f\" lon=\"%f\">",self.lat,self.lon];
if(self.ele!=0.0) {
[tempTrackpointString appendString:@"\n\t<ele>%f</ele>"];
}
if (self.time!=nil) {
NSString *timeString = [self.gpxDateFormatter stringFromDate:time];
[tempTrackpointString appendFormat:@"\n\t<time>%@</time>",timeString];
}
[tempTrackpointString appendString:@"\n</trkpt>\n"];
return tempTrackpointString;
}
So what's dirty about this? A few things that I can see:
- I assume that the
NSMutableArray
contains only Location objects - I do not use a proper XML serializer
- I assume 0.0 is an illegal value which really it isn't
- I haven't tested this with huge numbers of Locations