我需要从我的网站下载一些图片。我使用来自应用程序的图像的 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) 应用程序仅下载第一张图像,为什么?这种方式下载多个图像是否正确?