在iOS下使用AFNetworking下载文件/图像? [英] Download a file / image with AFNetworking in iOS?

查看:92
本文介绍了在iOS下使用AFNetworking下载文件/图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I thought I had it figured out but I just can't get it to work. I have a method that is called on every URL in an array. This method have a URL of a picture that should be downloaded in specific path in a Application Support folder for offline use. But maybe I'm misinterpreting the methods in the AFNetwork library. My method looks like this:

- (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是我要下载的图像的直接链接。

PhotoURL is the direct link to the image that I want to download.

由于所有图像都调用了此方法,因此所有日志都被调用了几次,似乎是正确的。

Since this method is called for all the images, all logs is called several times, and seems to be correct.

推荐答案

这里有一些问题。首先,你为什么要使用 @autoreleasepool ?我认为这里没有必要。还有,你在使用ARC吗?对于我的其余部分,我会考虑这一点。

You have a few problems here. so first, why are you using @autoreleasepool? i think there is no need for this here. also, are you using ARC? i consider this, for the rest of my answer.

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

in AFNetworking there is a class called AFImageRequestOperation , so this would be a good idea for you to use. first, import it

#import "AFImageRequestOperation.h"

然后你可以创建一个对象

then you could create an object

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设备上运行。

now, in the success block, you got the UIImage you need. there you need to get the documents directory. your code will not work on an ios device.

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

然后你可以使用NSDatas writeToFile

and then you could use 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];
}

这篇关于在iOS下使用AFNetworking下载文件/图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆