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

梦想的初衷 提交于 2020-01-14 04:31:06

问题


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

回答1:


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:).



来源:https://stackoverflow.com/questions/6012612/iphone-downloading-data-asynchronously-with-nsurl-request-as-opposed-to-nsdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!