使用本机功能IOS下载多个图像

时间:2013-09-07 05:56:11

标签: iphone ios ios6

如何下​​载多个图像并将其保存到磁盘。  我正在使用的发送请求如下。

for(NSDictionary *image in [data objectForKey:@"Catalogues"])
{
    NSString *imurl =[image objectForKey:@"Image_Path"];
    NSLog(@"%@",imurl);



    NSString *urlstring =imurl;
    NSLog(@"demo %@",urlstring);
    NSURL *mailurl =[NSURL URLWithString:urlstring];
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:mailurl];
    NSOperationQueue *ques =[[NSOperationQueue alloc]init];



    [NSURLConnection sendAsynchronousRequest:request queue:ques completionHandler:^(NSURLResponse *respo, NSData *data, NSError *err) {


        UIImage *image = [UIImage imageWithData:data];
        UIImageView *im = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 150, 150)];
        im.image = image;
        [self.view addSubview:im];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",documentsDirectory] 

可用于多个图像的任何原生方法?

2 个答案:

答案 0 :(得分:1)

你可以像这样实现一个AsyncImage类

在AsyncImage.h文件中

#import <UIKit/UIKit.h>

@interface AsyncImage : UIView
{
    NSURLConnection* connection; 
NSMutableData* data; 
UIImageView *image;
UIActivityIndicatorView *scrollingWheel;
    NSString *imgName;
}

-(void)loadImageFromString:(NSString*)url;
-(void)loadImageFromURL:(NSURL*)url;
-(void)setLocalImage:(UIImage *)localImage;

-(id) initWithFrame:(CGRect)frame;
-(NSString *)applicationDocumentsDirectory;
-(void)cancelConnection;

@end

在AsyncImage.m文件中

#import "AsyncImage.h"

@implementation AsyncImage

-(id)initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame]))
    {
    scrollingWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    float x = self.bounds.size.width/2;
    float y = self.bounds.size.height/2;
    scrollingWheel.center = CGPointMake(x, y);
    scrollingWheel.hidesWhenStopped = YES;
    [self addSubview:scrollingWheel];
    self.clipsToBounds = YES;
    }
    return self;
}

-(void)loadImageFromString:(NSString*)url
{
[scrollingWheel startAnimating];
if (connection!=nil) { 
    [connection release];
    connection = nil;
}
if (data!=nil) { 
    [data release];
    data = nil;
}
if (image != nil) {
    [image removeFromSuperview];
    image = nil;
}
    imgName = [[[url componentsSeparatedByString:@"/"] lastObject]retain];
    //    NSLog(@"imgName=%@",imgName);
    NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];   
    //    NSLog(@"imagePath=%@",imagePath);
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    if ([fileManager fileExistsAtPath:imagePath] == NO)
    {
        NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    } else {
        UIImage *img = [[UIImage alloc]initWithContentsOfFile:imagePath];
        image = [[[UIImageView alloc] initWithImage:img] autorelease];
    image.contentMode = UIViewContentModeScaleToFill;
    image.frame = self.bounds;
    [self addSubview:image];
    [scrollingWheel stopAnimating];
    }
}

-(void)setLocalImage:(UIImage *)localImage
{
    if (image != nil) {
    [image removeFromSuperview];
    image = nil;
    }
    image = [[[UIImageView alloc] initWithImage:localImage] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
}

//for URL
-(void)loadImageFromURL:(NSURL*)url
{
[scrollingWheel startAnimating];
if (connection!=nil) { 
    [connection release];
    connection = nil;
}
if (data!=nil) { 
    [data release];
    data = nil;
}
if (image != nil) {
    [image removeFromSuperview];
    image = nil;
}
    NSString *strurl=[NSString stringWithFormat:@"%@",url];
    imgName = [[[strurl componentsSeparatedByString:@"/"] lastObject]retain];
    NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];   
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    if ([fileManager fileExistsAtPath:imagePath] == NO)
    {
        NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    } else {
        UIImage *img = [[UIImage alloc]initWithContentsOfFile:imagePath];
        image = [[[UIImageView alloc] initWithImage:img] autorelease];
    image.contentMode = UIViewContentModeScaleToFill;
    image.frame = self.bounds;
    [self addSubview:image];
    [scrollingWheel stopAnimating];
    }
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [data release]; 
data=nil;
    [scrollingWheel stopAnimating];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData data] retain];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)dataObj
{
[data appendData:dataObj];
}

-(void) connectionDidFinishLoading:(NSURLConnection *)theConnection
{
[connection release];
connection=nil;
    NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
    [data writeToFile:imagePath atomically:YES];
image = [[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
[data release]; 
data=nil;
[scrollingWheel stopAnimating];
}

-(void)dealloc
{
[scrollingWheel release];
    [super dealloc];
}

-(NSString *)applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}

-(void)cancelConnection
{
    if (connection !=nil) {
        [connection cancel];
        connection=nil;
    }
    if(data!=nil){
        [data release]; 
        data=nil;
    }
[scrollingWheel stopAnimating];
}

@end

并在您的viewController.m中,您可以导入此类并像这样调用它

AsyncImage *imgBOD = [[AsyncImage alloc] initWithFrame:CGRectMake(10, 46, 70, 70)];
[imgBOD loadImageFromString:[dictData objectForKey:@"image_path"]];
[self.view addSubview:imgBOD];

答案 1 :(得分:0)

此特定问题没有“原生方法”。

如果您只想将图像列表保存到磁盘,则可以通过不首先创建UIImages来改进您的方法,只需将数据视为二进制数据并直接保存到磁盘。

为了保持低内存占用量,实现NSURLConnection的委托方法,并将图像数据分段写入(追加)到目标文件作为块数据到达connection:didReceiveData:

后者最好通过创建一个专用类来解决,该类封装NSURLConnection和其他相关状态,并且是NSOperation的子类,并使用实现NSURLConnection委托的异步样式。

您也可以考虑使用第三方库。但是警告:几乎所有知名的第三方网络库都不允许您轻松地将中的数据写入文件。默认情况下,它们将所有接收的数据累积到一个NSMutableData对象中。这可能会增加你的记忆足迹,因为图像可能很大,因为你可以一次启动多个连接。

此外,不要一次启动两个以上的连接。