ios - 在iOS App中下载多个图像

标签 ios objective-c nsurlconnection nsurlrequest

我想将多个图像从URL下载到我的iOS App设备中。

//
//  ImageDownload.m
//

#import "ImageDownload.h"

@implementation ImageDownload {
    int *position;
    NSArray *downloableImages;
}

- (void)start:(NSArray *)images delegate:(id)delegate
{
    position = 0;
    downloableImages = images;

    NSUInteger *count = ((NSUInteger *)[downloableImages count]);
    NSLog(@"%d", count);

    [self startDownload];
}

- (void)startDownload
{
    NSUInteger *imageDataCount;

    NSArray *image;
    NSString *filename;
    NSString *fileurl;

    NSURLRequest *imageUrlRequest;

    image = [downloableImages objectAtIndex:position];

    NSLog(@"%d", position);

    NSArray *imageData = [image valueForKey:@"image"];
    imageDataCount = ((NSUInteger *)[imageData count]);

    if (imageDataCount > 0) {
        filename = [imageData objectAtIndex:0];
        fileurl = [imageData objectAtIndex:1];

        NSLog(@"%@", fileurl);

        imageUrlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:fileurl]];
        NSURLConnection *imageUrlConnection = [[NSURLConnection alloc] initWithRequest:imageUrlRequest delegate:self startImmediately:TRUE];
    } else {
        NSUInteger *count = ((NSUInteger *)[downloableImages count]);

        if (((NSUInteger *)position) < ((NSUInteger *)count - 1)) {
            position = position + 1;

            [self startDownload];
        }
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"finish image...");
    NSUInteger *count = ((NSUInteger *)[downloableImages count]);

    if (((NSUInteger *)position) < ((NSUInteger *)count - 1)) {
        position = position + 1;

        [self startDownload];
    }
}

@end

目前...我只检查下载位置和当前URL,
存在要下载的27个文件...但下载未一步一步进行...检查此输出:

位置:0
http ..... fichero00.jpg
完成下载

位置:4
http ..... fichero04.jpg
完成下载

位置:8
http ..... fichero08.jpg
完成下载

最佳答案

在.h文件中创建一个ivar NSOperationQueue *operationQueue;,然后在.m文件中将其初始化:

operationQueue = [[NSOperationQueue alloc] init];
operationQueue.maxConcurrentOperationCount = 1;

要下载图像,请创建一个采用图像URL并为每个图像调用的方法:
-(void)downloadImageAtURL:(NSURL *)imageURL {

    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:imageURL] queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        // Do something with your images here...
    };
}

关于ios - 在iOS App中下载多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15024261/

相关文章:

ios - 在 UITableView 中显示 NSMutableArray

ios - 如何从 Amazon S3 下载 - iOS

ios - 根据应用程序委托(delegate)中的 bool 值在详细 View Controller TableView 中选择值

android - MAILTO 电子邮件中的链接以开始一封新电子邮件

objective-c - NSTableViewCell.ImageView 设置位置?

ios - 为什么此 Objective C 代码会因 EXC_BAD_ACCESS code=1 而崩溃? (使用 block 语法和字典)

ios - NSURLConnection 有效,但 AFNetworking 无效(在特定 URL 上)

objective-c - 如何在等待 NSURL 连接完成时阻止 objective-c 方法的执行?

Objective-C:不使用委托(delegate)方法的异步/后台 POST?

ios - 将可选字符串转换为日期