1

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

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] 

任何可用于多个图像的本机方法?

4

2 回答 2

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];
于 2013-09-07T06:11:15.460 回答
0

对于这个特定问题,没有“本机方法”。

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

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

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

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

此外,不要同时启动两个以上的连接。

于 2013-09-07T10:45:35.163 回答