开发者

iPhone: Downloading data asynchronously with NSURL request as opposed to [NSData datawithContents ofURL]

开发者 https://www.devze.com 2023-03-06 15:11 出处:网络
Hi Im a newbie and Im trying to download geocoding data from googleapi webpage. I did it using this: code:

Hi Im a newbie and Im trying to download geocoding data from googleapi webpage. I did it using this: code:

        NSMutableString *urlStr = [[NSMutableString alloc] initWithString:temp];
        NSMutableString *address = [[NSMutableString alloc] initWithString:l.Address];
        [address appendString:@" "];
        [address appendString:l.CityName];
        [address appendString:@" "];
        [address appendString:l.State];
        [address appendString:@" "];
        [address appendString:l.PostalCode];
        NSArray *addressArray = [address componentsSeparatedByString:@" "];
        [address release];
        NSString *a = [addressArray componentsJoinedByString:@"+"];
        [urlStr appendString:a];
        [urlStr appendString:@"&sensor=false"];
        NSURL *url = [[NSURL alloc] initWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        NSData *data = [NSData dataWithContentsOfURL:开发者_开发知识库url];

It worked fine but the glitch was that it locked up my GUI since it was all done synchronously.

Someone suggested I do it asynchronously using NSURLrequest. So I went to the apple website. from there I saw their example. However, Im still stuck. How do I convert the above code which is a synchronous request to an asynchronous one? So far this is what I have, but Im not sure if this works...... a bit confused ... could someone please point me in the righ direction with this code?

        NSURL *url = [[NSURL alloc] initWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        //create NSURL request for asynchronous processing
        NSURLRequest *theRequest = [NSURLRequest requestWithURL:url
                                                  cachePolicy:NSURLRequestUseProtocolCachePolicy
                                              timeoutInterval:60.0];

        NSURLConnection *theConnection= [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

        if (theConnection) 
           {
            receivedData = [[NSMutableData data] retain];
           }
        else
           {
            // Inform the user that the connection failed.
           }


Using NSURLConnection

Depending on how you structure your code, you'll want to act or notify some other object (delegate, notification) on successful completion (connectionDidFinishLoading:) or failure (connection: didFailWithError:).

0

精彩评论

暂无评论...
验证码 换一张
取 消