Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6800991
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T19:02:35+00:00 2026-05-26T19:02:35+00:00

I am using the code in this question NSURLConnection download large file (>40MB) to

  • 0

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;
}   
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T19:02:36+00:00Added an answer on May 26, 2026 at 7:02 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using the BlockingQueue code posted in this question , but realized I
I am using the code I posted as an answer to this question to
i took this code from a different question and my script file has more
This questions involves 2 different implementations of essentially the same code. First, using delegate
Using this code to zip a folder and it works perfect on small files
Im using this code for mysql connection $con = mysql_connect(localhost:/var/lib/mysql/mysql.sock, abc , xyz); if
While using this code to serialize an object: public object Clone() { var serializer
When using this code (simplified for asking): var rows1 = (from t1 in db.TABLE1
Im using this code: $(this).css('backgroundcolor', localStorage.getItem('bgColorr') + !important;); When i write: alert( localStorage.getItem('bgColorr') +
I have this code :- using (System.Security.Cryptography.SHA256 sha2 = new System.Security.Cryptography.SHA256Managed()) { .. }

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.