0

私のウェブサイトから画像をダウンロードする必要があります。アプリから画像の 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) を追加すると、アプリが最初の画像のみをダウンロードするのはなぜですか? 複数の画像をダウンロードする場合、この方法は正しいですか?

4

2 に答える 2

1

self.imgDataループ内で割り当てている可能性があります。配列内の画像のダウンロードについては、このリンクを参照してください:非同期の画像のダウンロードとは何ですか?

于 2013-02-06T09:39:57.490 に答える
1

self.imgConnection が for ループで何度も上書きされるようです。したがって、インターネットからの接続に対する応答を受け取るまでに、ループはそれを何度も上書きし、最後に割り当てられたオブジェクトを最終的に保持します。そうすれば、else if(connection==self.imgConnection) は一度だけ真になります。

ここでのベスト プラクティスは、接続の種類ごとに 1 つのクラスを作成することです。これにより、接続クラスの 1 つのインスタンスを使用して 1 つのイメージをダウンロードし、そのインスタンス内に保持してから、呼び出し元クラスに渡すことができます。

于 2013-02-06T09:40:32.293 に答える