What is asynchronous image downloading and how can I download too many images?
I ha开发者_Go百科ve too many images to be download from net into iPhone? How can I build an application using asynchronous image downloading?.
Most common and simple way is to use NSURLConnection with asynchronous request. Create connection with request set delegate, and it starts load data in background calling delegate methods when receive next chunk of data, finish load or fail. when first object is loaded, start next and so on. Here is slightly simplified working code:
- (id)init...{
//...
requestData = [[NSMutableData alloc] initWithCapacity:1000000];
myImages = [[NSMutableArray alloc] initWithCapacity:100];
myImagesAddresses = [[NSMutableArray alloc] initWithCapacity:100];
[myImagesAddresses addObject:@"http://mysite.com/image1"];
[myImagesAddresses addObject:@"http://mysite.com/image2"];
//...
[self loadNextImage];
//...
}
-(void)loadNextImage{
if ([myImagesAddresses count]){
NSURL * imageURL = [NSURL URLWithString:[myImagesAddresses lastObject]];
NSURLRequest * myRequest = [NSURLRequest requestWithURL:imageURL];
[[NSURLConnection alloc] initWithRequest:myRequest delegate:self];
NSLog(@"start load URL:%@", imageURL);
}
else{
NSLog(@"No more images to load");
// all images are ready to use!
}
}
// connection delegate methods
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data{
NSLog(@"more data...");
[requestData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)inConnection{
[myImages addObject:[UIImage imageWithData:[NSData dataWithData:requestData]]];
[inConnection release];
inConnection = nil;
NSLog(@"Image from:%@ loaded",[myImagesAddresses lastObject]);
[myImagesAddresses removeLastObject];
[self loadNextImage];
}
- (void)connection:(NSURLConnection *) inConnection didFailWithError:(NSError *)error{
[inConnection release];
inConnection = nil;
NSLog(@"Image from:%@ not loaded",[myImagesAddresses lastObject]);
[myImagesAddresses removeLastObject];
[self loadNextImage];
}
精彩评论