我想在iOS App中将多个图像从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
目前......我只检查下载位置和当前网址, 存在27个要下载的文件...但是下载不是一个一个......检查此输出:
位置:0
HTTP ..... fichero00.jpg
完成下载职位:4
HTTP ..... fichero04.jpg
完成下载职位:8
HTTP ..... fichero08.jpg
完成下载
答案 0 :(得分: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...
};
}
答案 1 :(得分: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
}
希望这有助于!!!
答案 2 :(得分: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
答案 3 :(得分: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