1

我想在 iOS 应用程序中从 URL 下载多个图像到我的设备。

//
//  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
完成下载

4

4 回答 4

3

在你的 .h 文件中创建一个 ivarNSOperationQueue *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...
    };
}
于 2013-02-22T12:51:20.687 回答
2

你可以试试这个代码。它 100% 为我工作

您可以在此处获得更多参考

-(IBAction)startdownload
{
for (int i=0; i<[downloadarray count]; i++)   //download array have url links
{ 
NSURL *URL = [NSURL URLWithString:[downloadarray objectAtIndex:i]];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]initWithURL:URL];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue  completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
  if([data length] > 0 && [[NSString stringWithFormat:@"%@",error] isEqualToString:@"(null)"])
{
 //make your image here from data.
 UIImage *imag = [[UIImage alloc] initWithData:[NSData dataWithData:data]];
 NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES);
 NSString *docDir = [array objectAtIndex:0];
 NSString *imgstr=[NSString stringWithFormat:@"%d",i];
 NSString *pngfilepath = [NSString stringWithFormat:@"%@sample%@.png",docDir,imgstr];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(imag)];
 [data1 writeToFile:pngfilepath atomically:YES];
  }
 else if ([data length] == 0 && [[NSString stringWithFormat:@"%@",error] isEqualToString:@"(null)"])
{
  NSLog(@"No Data!");
}
  else if (![[NSString stringWithFormat:@"%@",error] isEqualToString:@"(null)"]){
 NSLog(@"Error = %@", error);
 }
}];

 }

 -(IBAction)viewfile
 {
 NSMutableArray *arr=[[NSMutableArray alloc]init];

  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,   NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0];
 NSString *pngfilepath = [NSString stringWithFormat:@"%@",documentsDirectory];
 NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:pngfilepath error:&error];
 for (int i=0; i<[filePathsArray count]; i++){
 NSString *pngfilepath = [NSString stringWithFormat:@"%@%@",documentsDirectory,  [filePathsArray objectAtIndex:i]];
 [arr addObject:[UIImage imageWithContentsOfFile:pngfilepath]];
 }
myimageview = [[UIImageView alloc] initWithImage:[arr objectAtIndex:0]]; //Here myimageview is UIImageView

 }

希望这可以帮助!!!

于 2013-02-22T12:48:08.903 回答
1

解决 NSOperationQueue 它允许您控制同时运行多少操作。

创造:

NSOperationQueue *queue = [NSOperationQueue new];
queue.maxConcurrentOperationCount = 1;

然后添加操作:

NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
    ... here is you code with converting image to data and addition it to NSURLConnection
}];
[operation setCompletionBlock:^{
    ....something that you want to do, after operation completes
}];
[queue addOperation:operation];

有关 NSOperation 的更多信息: https ://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html#//apple_ref/occ/cl/NSOperation

于 2013-02-22T12:42:56.337 回答
0

这是我的新代码...尝试更新 UIProgressView 时出现延迟

//
//  ImageDownload.m
//

#import "ImageDownload.h"

@implementation ImageDownload {
    NSMutableArray *downloableImages;
    int position;

    Sync *mySync;
}

- (void)start:(NSArray *)images sync:(Sync *)sync
{
    NSArray *imageData;
    int imageDataCount;

    mySync = sync;
    downloableImages = [[NSMutableArray alloc] init];

    for (NSArray *image in images) {
        imageData = [image valueForKey:@"image"];
        imageDataCount = [imageData count];

        if (imageDataCount > 0) {
            [downloableImages addObject:imageData];
        }
    }

    [self downloadAllFiles];
}

- (void)downloadAllFiles
{
    NSString *filename;
    NSString *fileUrl;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDirectory = [paths objectAtIndex:0];

    position = 0;
    int count = [downloableImages count];

    NSLog(@"%@", downloableImages);
    NSLog(@"total files %d", count);

    for (NSArray *image in downloableImages) {
        filename = [image objectAtIndex:0];
        fileUrl = [image objectAtIndex:1];

        NSURL *url = [NSURL URLWithString:fileUrl];
        NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];

        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
            position++;

            float progress = (float)position / (float)count;
            //update UIProgressView
            [mySync setProgressImageDownload:progress];

            if ([data length] > 0 && [[NSString stringWithFormat:@"%@", error] isEqualToString:@"(null)"]) {
                UIImage *downloadedImage = [[UIImage alloc] initWithData:[NSData dataWithData:data]];
                NSString *imageDestinationPath = [NSString stringWithFormat:@"%@%@", cacheDirectory, filename];

                NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(downloadedImage, 100.0)];
                [imageData writeToFile:imageDestinationPath atomically:YES];
            }

            if (position == count) {
                NSLog(@"all complete...");

                [mySync downloadImagesComplete];
            }
        }];
    }
}

@end
于 2013-02-22T17:35:00.807 回答