2013-02-22 3 views
1

Я хочу загрузить несколько изображений из URL-адреса на устройство в приложении iOS.скачать несколько изображений в приложении iOS

// 
// 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, Exists 27 файлов для загрузки ... но загрузка не идет по одному ... проверить этот вывод:

Должность: 0
HTTP ..... fichero00.jpg
Finish загрузить

Позиция: 4
HTTP ..... fichero04.jpg
Finish загрузить

Должность: 8
HTTP ..... fichero08.jpg
Finish загрузить

ответ

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

2

Вы можете попробовать этот код .. Его 100% Работа для меня

You can get more reference here

-(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 

} 

Надеюсь, что это поможет !!!

+0

Привет, я пробую этот метод ... отлично работает, чтобы скачать ... но у меня проблема, когда я пытаюсь обновить progressView !!! «completeHandler» на самом деле, когда загрузка завершена?, Потому что у меня есть задержка при обновлении progressView ... – jfrubiom

+0

@jfrubiom Может ли показать вашу часть обработчика завершения для просмотра прогресса? – Dany

+0

Привет, я переформулирую свой вопрос здесь http: /stackoverflow.com/questions/15037791/ios-some-problems-during-download-multiple-images-and-update-uiprogressview – jfrubiom

3

Создать Ивар NSOperationQueue *operationQueue; в вашем файле .h и инициализировать его в файле .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... 
    }; 
} 
+0

Как я могу показать ход общей загрузки (всех изображений) с помощью этого метода? –

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 
Смежные вопросы