MapViewController.h:
.....
NSMutableData *webData;
KMLParser *kml;
.....
@property (nonatomic, retain) NSMutableData *webData;
MapViewController.m:
- (IBAction)showKmlData:(id)sender //Let's say you want to download kml data with a button tap, you create a method for that (you may not act like this, but the content is the same):
{
NSURL *path = [NSURL URLWithString:@"http://www.domain.com/route.kml"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:path];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.webData =[NSMutableData data];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *fileName = [[[NSURL URLWithString:kmlStr] path] lastPathComponent];
//NSString *fileName = @"route.kml";
NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [pathArr objectAtIndex:0];
NSString *filePath = [folder stringByAppendingPathComponent:fileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSError *writeError = nil;
[webData writeToURL: fileURL options:0 error:&writeError];
if( writeError) {
NSLog(@" Error in writing file %@' : \n %@ ", filePath , writeError );
return;
}
kml = [[KMLParser parseKMLAtPath:filePath] retain];
NSArray *annotations = [kml points];
if ([[mapview overlays] count] == 0) {
[mapview addAnnotations:annotations];
NSArray *overlays = [kml overlays];
[mapview addOverlays:overlays];
MKMapRect flyTo = MKMapRectNull;
for (id <MKOverlay> overlay in overlays) {
if (MKMapRectIsNull(flyTo)) {
flyTo = [overlay boundingMapRect];
} else {
flyTo = MKMapRectUnion(flyTo, [overlay boundingMapRect]);
}
}
for (id <MKAnnotation> annotation in annotations) {
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
if (MKMapRectIsNull(flyTo)) {
flyTo = pointRect;
} else {
flyTo = MKMapRectUnion(flyTo, pointRect);
}
}
mapview.visibleMapRect = flyTo;
}
[mapview addAnnotations:annotations];
NSArray *overlays = [kml overlays];
[mapview addOverlays:overlays];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"An error has occured." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}