The API supplied with UIKit for retrieving data from a URL is asynchronous, so as to leave the UI responsive. It uses the interface NSURLConnectionDelegate. You should implement that interface in order to receive the data asynchronously.
First you initialize the retrieval from the URL like this:
NSURLRequest *theRequest=[NSURLRequest requestWithURL:anUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:CONNECTION_TIMEOUT];
// create the connection with the request
// and start loading the data
urlConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (urlConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
self.receivedData = [NSMutableData data];
} else {
// Inform the user that the connection failed.
NSLog(@"Failed to create connection to URL: %@.", anUrl);
}
Here the class containing this code is set as the delegate, so this class should be declared as implementing the named interface:
@interface MyClass : NSObject <NSURLConnectionDelegate> {
}
// URLConnection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse;
A current implementation of mine looks like this:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// This method is called when the server has determined that it
// has enough information to create the NSURLResponse.
// It can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
// receivedData is an instance variable declared elsewhere.
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// Do error handling here
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
// Now process the received data accumulated in receivedData.
}
-(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
return cachedResponse;
}
This should get you going.