optimising multiple asynchronous image downloads i

2019-04-15 23:47发布

I want to download a lot of pictures from the server. How can I do this as fast as possible? Currently I am using:

UIImage* myImage = [UIImage imageWithData: 
[NSData dataWithContentsOfURL: 
[NSURL URLWithString: @"http://example.com/image.jpg"]]];

It is painfully slow. Is there any speed increase in downloading multiple images at the same time (asynchronously), and if so how many is too many?

1条回答
仙女界的扛把子
2楼-- · 2019-04-16 00:00

You won't get a definitive answer to the optimal number of connections, because there is none. It just depends on several variables such as bandwidth, image size or your own patience. You need to measure this by yourself to get it right.

Doing asynchronous requests won't increase the downloading speed, but the user experience is way better. Seriously, you should consider doing it for any download that takes more than a second.

I always recommend using ASIHTTPRequest, it makes implementing things such as queues and progress bars easy.

Here's the simplest example from an asynchronous request using the library:

- (IBAction)grabURLInBackground:(id)sender
{
   NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
   ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
   [request setDelegate:self];
   [request startAsynchronous];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
   // Use when fetching text data
   NSString *responseString = [request responseString];

   // Use when fetching binary data
   NSData *responseData = [request responseData];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
   NSError *error = [request error];
}

Update: This library will no longer be supported. From 1:

"Please note that I am no longer working on this library - you may want to consider using something else for new projects. :)"

Nowadays I use AFNetworking for most of my projects.

查看更多
登录 后发表回答