什么是异步下载图像,我怎么能下载太多的图像? [英] What is asynchronous image downloading and how can I download too many images?

查看:130
本文介绍了什么是异步下载图像,我怎么能下载太多的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有太多的图片是从网上下载到iPhone?我如何使用异步下载图像构建一个应用程序?

I have too many images to be download from net into iPhone? How can I build an application using asynchronous image downloading?.

推荐答案

最常见和简单的方法是使用NSURLConnection的异步请求。创建请求集代表连接,并在后台接收数据的下一个块,完成负载或无法启动时加载数据调用委托方法。当加载第一个对象,下等上启动。
这里稍微简化的工作code:

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];
}

这篇关于什么是异步下载图像,我怎么能下载太多的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆