1

I am using the code in this question NSURLConnection download large file (>40MB) to download a KML file and load the data in my MKMap using the KMLViewer of Apple.KML files are small <200KB so KMLViewer is just fine.The code provided in the question should be fine too exept the fact that when the I click the button (that should make the request of the url and then load the data in the map) the map just goes to location 0,0 ,zooming tremendously and so all I can see is a black map.What is going wrong? What should I do? Here is the code: (By the way, I have two connections, because one uses JSON to get Google search results for locations from a UIsearchBar.)

EDIT 1

//In the ViewController.m
-(void) searchCoordinatesForAddress:(NSString *)inAddress //for Google location search
{
NSMutableString *urlString = [NSMutableString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@?output=json",inAddress];

[urlString setString:[urlString stringByReplacingOccurrencesOfString:@" " withString:@"+"]];

NSURL *url = [NSURL URLWithString:urlString];

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

[connection release];
[request release];
}


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[webData setLength:0]; //webData in the header file
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if ( connection = theConnection ) //theConnection is created before
{
[webData appendData:data];
}
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSDictionary *results = [jsonString JSONValue];

NSArray *placemark = [results objectForKey:@"Placemark"];
NSArray *coordinates = [[placemark objectAtIndex:0] valueForKeyPath:@"Point.coordinates"];

double longitude = [[coordinates objectAtIndex:0] doubleValue];
double latitude = [[coordinates objectAtIndex:1] doubleValue];

NSLog(@"Latitude - Longitude: %f %f", latitude, longitude);

[self zoomMapAndCenterAtLatitude:latitude andLongitude:longitude];

[jsonString release];

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

NSString *fileName = [[[NSURL URLWithString:kmlStr] path] lastPathComponent];
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;
}
NSLog(@"%@",fileURL);
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error !" message:@"Error has occured, please verify internet connection.."  delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];

[alert show];
[alert release];
}

-(IBAction)showKmlData:(id)sender
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"KMLGenerator" ofType:@"kml"];

kml = [[KMLParser parseKMLAtPath:path] retain];

NSArray *overlays = [kml overlays];
[mapview addOverlays:overlays];

NSArray *annotations = [kml points];
[mapview addAnnotations:annotations];

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

EDIT 2 I have done modifications,now it doesn't go anywhere, it crashes because it doesn't find KMLGenerator.kml file (path)

-(void)showData 
{

NSString *url = /*kmlStr;*/@"http://www.ikub.al/hartav2/handlers/kmlgenerator.ashx?layerid=fc77a5e6-5985-4dd1-9309-f026d7349064&kml=1";
NSURL *path = [NSURL URLWithString:url];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:path];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
theConnection = connection;
[connection release];
[request release];

}

//Search Coordinates for address entered in the searchBar
-(void) searchCoordinatesForAddress:(NSString *)inAddress
{
NSMutableString *urlString = [NSMutableString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@?output=json",inAddress];

[urlString setString:[urlString stringByReplacingOccurrencesOfString:@" " withString:@"+"]];

NSURL *url = [NSURL URLWithString:urlString];

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

[connection release];
[request release];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0]; //Here i get an alert: NSData may not respond to -setLength
                           //webData is a NSData object.
}


-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data]; //Here i get an alert: NSData may not respond to -appendData
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if ( connection == theConnection ) //"theConnection" is for kml file download
    {
        NSString *fileName = [[[NSURL URLWithString:kmlStr] path] lastPathComponent];
        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;
        }

        NSLog(@"%@",fileURL);
    }
    else //it's a geocoding result
    {
        NSString *jsonString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];

        NSDictionary *results = [jsonString JSONValue];

        //check the Google geocode error code before looking for coordinates...        
        NSDictionary *statusDict = [results objectForKey:@"Status"];
        NSNumber *errorCode = [statusDict objectForKey:@"code"];
        if ([errorCode intValue] == 200)  //200 is "success"
        {
            NSArray *placemark = [results objectForKey:@"Placemark"];
            NSArray *coordinates = [[placemark objectAtIndex:0] valueForKeyPath:@"Point.coordinates"];

            double longitude = [[coordinates objectAtIndex:0] doubleValue];
            double latitude = [[coordinates objectAtIndex:1] doubleValue];

            NSLog(@"Latitude - Longitude: %f %f", latitude, longitude);

            [self zoomMapAndCenterAtLatitude:latitude andLongitude:longitude];
        }
        else
        {
            NSLog(@"geocoding error %@", errorCode);
        }

        [jsonString release];
    }
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Error has occured, please verify internet connection..." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}


- (IBAction)showKmlData:(id)sender
{

NSString *path = [[NSBundle mainBundle] pathForResource:@"KMLGenerator" ofType:@"kml"];

kml = [[KMLParser parseKMLAtPath:path] retain];

NSArray *annotationsImmut = [kml points];
NSMutableArray *annotations = [annotationsImmut mutableCopy];
//[mapview addAnnotations:annotations];
[self filterAnnotations:annotations];

MKMapRect flyTo = MKMapRectNull;

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;
}   
Community
  • 1
  • 1
  • You'll need to do some debugging using breakpoints and NSLogs to narrow down the location of the problem and post that code. There are too many possible points of failure in what you describe to make a reasonable guess. –  Oct 31 '11 at 16:47
  • Added some code and updated question.Thanks. –  Nov 12 '11 at 21:18

1 Answers1

1

It's still hard to pinpoint the cause but there are some problems with the code you posted.

First, in didReceiveData, this line is probably not what you want:

if ( connection = theConnection ) //theConnection is created before

The single = is doing an assignment instead of an equality check (which is ==).

Fixing that, however, is not the solution (the other problem is in connectionDidFinishLoading).

The didReceiveData method is not the right place to process your geocoding JSON result. The didReceiveData method can be called multiple times for a single url request. So it's possible that the geocoding results (just like the kml file) may be delivered in multiple chunks which cannot be processed individually in that method. The data in that method may be a partial stream of the complete result which will not make sense to process. You should only be appending the data to an NSMutableData object or, as an answer to the linked question suggests, write the data to a file.

The data can only be processed/parsed in the connectionDidFinishLoading method.

Since you are using the same connection delegate for both the kml file download and the geocoding, they both call the same connectionDidFinishLoading method. In that method, you are not checking which connection it is being called for.

When the geocoding url request finishes and calls connectionDidFinishLoading, that method takes whatever is in webData (possibly the geocoding results or empty data) and writes it to the kmlStr file. This is probably what causes the kml data to show "nothing".

You have to move the processing of the geocoding results to connectionDidFinishLoading and check there what connection is calling it.

For example:

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if ( connection == theConnection ) //"theConnection" is for kml file download
    {
        NSString *fileName = [[[NSURL URLWithString:kmlStr] path] lastPathComponent];
        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;
        }
        NSLog(@"%@",fileURL);
    }
    else //it's a geocoding result
    {
        NSString *jsonString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];

        NSDictionary *results = [jsonString JSONValue];

        //check the Google geocode error code before looking for coordinates...        
        NSDictionary *statusDict = [results objectForKey:@"Status"];
        NSNumber *errorCode = [statusDict objectForKey:@"code"];
        if ([errorCode intValue] == 200)  //200 is "success"
        {
            NSArray *placemark = [results objectForKey:@"Placemark"];
            NSArray *coordinates = [[placemark objectAtIndex:0] valueForKeyPath:@"Point.coordinates"];

            double longitude = [[coordinates objectAtIndex:0] doubleValue];
            double latitude = [[coordinates objectAtIndex:1] doubleValue];

            NSLog(@"Latitude - Longitude: %f %f", latitude, longitude);

            [self zoomMapAndCenterAtLatitude:latitude andLongitude:longitude];
        }
        else
        {
            NSLog(@"geocoding error %@", errorCode);
        }

        [jsonString release];
    }
}

(It's probably better to avoid using the same delegate for multiple connections. It would be cleaner to move the geocoding out to another class with its own connection object and delegate methods. By the way, iOS5 has geocoding built-in so you don't need to do this yourself. See the CLGeocoder class.)

I added a check for the Google error code. It's possible the address queried returns no results in which case there will be no placemark coordinates in which case the latitude and longitude will get set to zero. This is another possible cause of the map going to 0,0.

It also seems you are using the deprecated v2 Google geocoder. This is the latest one but you may want to switch to using CLGeocoder instead unless you need to support iOS4 or earlier.

  • I have updated my question with the results and refreshed code.Google geocoder is still the same, I'll modify it in the end,hopefully after everything else will be fine. –  Nov 22 '11 at 16:20
  • `webData` needs to be declared as `NSMutableData` (not `NSData`). –  Nov 22 '11 at 18:51
  • I assume it's crashing in `showKmlData` when it tries to read KMLGenerator.kml from the main bundle. Reading from the main bundle means that file has to be added to the project at _build_ time. Maybe what you are trying to do is read the kml file created in `connectionDidFinishLoading`? That file is created at _run_ time in the _Documents_ folder which is not the same as the main bundle. –  Nov 23 '11 at 21:41
  • Another thing is I don't see where you are creating (alloc+init) the `webData` variable. If you don't do that, it will stay nil and all calls to it will do nothing and you end up with no data (and no file). The `writeToURL` won't even return an error because messages sent to nil objects do nothing. What I suggest is change `webData` to a retain property and in `didReceiveResponse` do `self.webData = [NSMutableData data];` instead of the `setLength`. –  Nov 23 '11 at 21:46
  • For reading the kml file back (assuming you want to read the file created in the Documents folder), create the file path the same way it is being set when writing the file. –  Nov 23 '11 at 21:54
  • I am trying these right now.Another question: In `NSString *fileName = [[[NSURL URLWithString:kmlStr] path] lastPathComponent];` i assume that the URL must be of type **www.site.com/file.txt** and therefore the name of the file will be file.txt , but in my case the url is kind of **www.site.com/dir/fileGenerator.aspx?fileId**, the file is generated dynamically, is not physically present in the server, but i know the name of output file, it is always the same `KMLGenerator.kml`.May I set the filename string directly as KMLGenerator.kml ? –  Nov 23 '11 at 22:16
  • Yes you can set the file name directly (eg. `NSString *fileName = @"KMLGenerator.kml";`). –  Nov 23 '11 at 22:23
  • Done all the things, was trying other mods but definitely nothing.The good news is that now it doesn't crash anymore.The bad news is that doesn't do anything.It does not go anywhere, if map is moved a little or zoomed in it zooms it out and resets it to its initial position,the default position.I don't know what to do anymore... –  Nov 24 '11 at 00:11
  • 1
    This is how development goes sometimes. Solving one problem just gets you to the next one. You'll need to do some debugging. That means understanding how the code works, what it's doing, etc. Put NSLogs, add breakpoints, step through the code in the debugger and check variable values. –  Nov 24 '11 at 00:17
  • Yes, I see, it gets a little frustrating.After some debugging and after some breakpoints : I get an error at line `NSString *fileName = @"KMLGenerator.kml";` in the showKMLData method.You see, i did create the file path the same way it was being set when writing the file. –  Nov 24 '11 at 00:55