异步下载 - 右侧模式

时间:2013-02-06 09:20:26

标签: ios iphone asynchronous download nsurlconnection

我需要从我的网站下载一些图片。我用应用程序中的图像的url创建了一个XML文件,然后我读取了这个文件并将所有url存储在一个数组中。

现在,我需要下载所有图片,我想要它同步,我想知道最好的方法,现在我的代码是:

    for (int i=0; i<self.arrayAggiornamenti.count; i++) {

        Aggiornamento *aggiornamento = [self.arrayAggiornamenti objectAtIndex:i];
        NSMutableArray *arrayPath = aggiornamento.arrayPaths;

        for (int j=0; j<arrayPath.count; j++) {

            NSString *urlString = [NSString stringWithFormat:@"http://www.xxx.com/%@",[arrayPath objectAtIndex:j]];

            NSString *urlStringEncoded = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

            NSURL *urlImage = [NSURL URLWithString:urlStringEncoded];

            NSURLRequest *requestImgage = [NSURLRequest requestWithURL:urlImage
                                                        cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                    timeoutInterval:60];

            self.imgData = [[NSMutableData alloc] init];

            self.imgConnection = [[NSURLConnection alloc] initWithRequest:requestImgage delegate:self startImmediately:YES];
        }
}

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

    // Start parsing XML
    if (connection == self.xmlConnection) {
    }
    // Start download Totale
    else if (connection == self.toatalConnection) {
    }
    // Start connessione immagini
    else {        
        [self.imgData writeToFile:pathFile atomically:YES];
    }
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    if (connection == self.xmlConnection) {
    }
    else if (connection == self.toatalConnection) {
    }
    else {
        [self.imgData appendData:data];
    }

}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {

    if (connection == self.xmlConnection) {
    }
    else if (connection == self.toatalConnection) {
    }
    else if (connection == self.imgConnection){
    }
}

使用此代码下载图像,但问题是,如果我在didReciveResponse上添加if else(connection == self.imgConnection),应用程序只下载第一张图片,为什么? 下载多个图像的方式是否正确?

2 个答案:

答案 0 :(得分:1)

可能是因为你在循环中分配self.imgData。 请参阅此链接以下载阵列中的图像:What is asynchronous image downloading and how can I download too many images?

答案 1 :(得分:1)

看起来self.imgConnection在for循环中一次又一次地被覆盖。因此,当您收到来自互联网的任何连接的响应时,循环将多次覆盖它,它将最终保留最后分配的对象。这样,你的else if(connection == self.imgConnection)只会出现一次。

此处的最佳做法是为每种类型的连接创建一个类。通过这种方式,您将能够使用一个连接类实例下载一个图像,并将其保存在该实例中,然后将其传递给您的调用者类。

相关问题