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個あります...しかし、ダウンロードは1つずつ実行されません...次の出力を確認してください。

位置:0
http.....fichero00.jpg
ダウンロード を終了

位置:4
http.....fichero04.jpg
ダウンロード を終了

位置:8
http.....fichero08.jpg
ダウンロード を終了

4

4 に答える 4

3

.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...
    };
}
于 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 に答える