在iOS下使用AFNetworking下载文件/图像?

时间:2012-06-25 09:41:39

标签: iphone objective-c ios ipad afnetworking

我以为我已经弄明白了,但我无法让它发挥作用。 我有一个方法,在数组中的每个URL上调用。 此方法具有应在Application Support文件夹中的特定路径中下载以供脱机使用的图片的URL。 但也许我误解了AFNetwork库中的方法。 我的方法如下:

- (void) downloadImageInBackground:(NSDictionary *)args{

  @autoreleasepool {

    NSString *photourl = [args objectForKey:@"photoUrl"];
    NSString *articleID = [args objectForKey:@"articleID"];
    NSString *guideName = [args objectForKey:@"guideName"];
    NSNumber *totalNumberOfImages = [args objectForKey:@"totalNumberOfImages"];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:photourl]];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.inputStream = [NSInputStream inputStreamWithURL:[NSURL URLWithString:photourl]];

    [operation setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{
        DLog(@"PROBLEMS_AF");
    }];
    DLog(@"URL_PHOTOURL: %@", photourl);
    DLog(@"indexSet: %@", operation.hasAcceptableStatusCode); 
    [operation  response];

    NSData *data = [args objectForKey:@"data"];

    NSString *path;
    path = [NSMutableString stringWithFormat:@"%@/Library/Application Support/Guides", NSHomeDirectory()];
    path = [path stringByAppendingPathComponent:guideName];
    NSString *guidePath = path;
    path = [path stringByAppendingPathComponent:photourl];

    if ([[NSFileManager defaultManager] fileExistsAtPath:guidePath]){
        [[NSFileManager defaultManager] createFileAtPath:path
                                                contents:data
                                              attributes:nil];
    }

    DLog(@"path: %@", path);
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
    [operation start];


    DLog(@"isExecuting: %d",[operation isExecuting]);
    DLog(@"IS_FINISHED: %d",[operation isFinished]);


  }

} 

PhotoURL是我要下载的图片的直接链接。

由于为所有图像调用了此方法,因此会多次调用所有日志,并且这些日志似乎是正确的。

2 个答案:

答案 0 :(得分:40)

这里有一些问题。首先,你为什么要使用@autoreleasepool?我认为这里没有必要这样做。还有,你在使用ARC吗?我认为这是我的其余部分。

在AFNetworking中有一个名为AFImageRequestOperation的类,所以这对你来说是个好主意。首先,导入它

#import "AFImageRequestOperation.h"

然后你可以创建一个对象

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:photourl]];
AFImageRequestOperation *operation;
operation = [AFImageRequestOperation imageRequestOperationWithRequest:request 
    imageProcessingBlock:nil 
    cacheName:nil 
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

    } 
    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
        NSLog(@"%@", [error localizedDescription]);
    }];

现在,在成功模块中,您获得了所需的UIImage。 你需要获取文件目录。您的代码无法在ios设备上运行。

// Get dir
NSString *documentsDirectory = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
NSString *pathString = [NSString stringWithFormat:@"%@/%@",documentsDirectory, guideName];

然后您可以使用NSDatas writeToFile

// Save Image
NSData *imageData = UIImageJPEGRepresentation(image, 90);
[imageData writeToFile:pathString atomically:YES];

最后,你需要开始操作

[operation start];

所有在一起:

- (void)downloadImageInBackground:(NSDictionary *)args{

    NSString *guideName = [args objectForKey:@"guideName"];
    NSString *photourl = [args objectForKey:@"photoUrl"];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:photourl]];

    AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request 
        imageProcessingBlock:nil 
        cacheName:nil 
        success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

            // Get dir
            NSString *documentsDirectory = nil;
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            documentsDirectory = [paths objectAtIndex:0];
            NSString *pathString = [NSString stringWithFormat:@"%@/%@",documentsDirectory, guideName];

            // Save Image
            NSData *imageData = UIImageJPEGRepresentation(image, 90);
            [imageData writeToFile:pathString atomically:YES];

        } 
        failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
            NSLog(@"%@", [error localizedDescription]);
        }];

    [operation start];
}

答案 1 :(得分:5)

这里的问题是,不保留操作。它将立即解除分配。

将操作设为您的类的属性,或让操作队列(也是属性)处理您的请求(推荐)。在后一种情况下,请不要致电[operation start]。 当您使用AFHTTPClient时,也将为您管理操作队列。

此外,您应该为请求操作注册完成回调(setCompletionBlockWithSuccess:failure:)。