在 iOS 中使用 AFNetworking 下载文件/图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11186854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download a file / image with AFNetworking in iOS?
提问by Joakim Engstrom
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:
我以为我已经弄清楚了,但我就是无法让它工作。我有一个在数组中的每个 URL 上调用的方法。此方法具有图片的 URL,应将其下载到 Application Support 文件夹中的特定路径中以供离线使用。但也许我误解了 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 is the direct link to the image that I want to download.
PhotoURL 是我要下载的图像的直接链接。
Since this method is called for all the images, all logs is called several times, and seems to be correct.
由于对所有图像都调用了此方法,因此所有日志都被调用了几次,似乎是正确的。
回答by choise
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.
你在这里有一些问题。所以首先,你为什么使用@autoreleasepool
?我认为这里没有必要。另外,你在使用ARC吗?我认为这一点,对于我的其余答案。
in AFNetworking there is a class called AFImageRequestOperation
, so this would be a good idea for you to use. first, import it
在 AFNetworking 中有一个名为 的类AFImageRequestOperation
,因此这对您来说是一个好主意。首先,导入它
#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]);
}];
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.
现在,在成功块中,您获得了所需的 UIImage。在那里您需要获取文档目录。您的代码将无法在 ios 设备上运行。
// Get dir
NSString *documentsDirectory = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
NSString *pathString = [NSString stringWithFormat:@"%@/%@",documentsDirectory, guideName];
and then you could use NSDatas writeToFile
然后你可以使用 NSDatas writeToFile
// Save Image
NSData *imageData = UIImageJPEGRepresentation(image, 90);
[imageData writeToFile:pathString atomically:YES];
at last, you need to start the operation
最后,您需要开始操作
[operation start];
all together:
全部一起:
- (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];
}
回答by Felix
The problem here is, the operation is not retained. It will be deallocated immediately.
这里的问题是,操作没有保留。它将立即解除分配。
Either make the operation a property of your class or let a operation queue (also a property) handle the request for you (recommended). In the latter case don't call [operation start]
.
When you use AFHTTPClient
the operation queue will also be managed for you.
要么使操作成为您的类的属性,要么让操作队列(也是一个属性)为您处理请求(推荐)。在后一种情况下,不要调用[operation start]
. 当您使用AFHTTPClient
操作队列时,也会为您管理。
Also you should register a completion callback for the request operation (setCompletionBlockWithSuccess:failure:
).
您还应该为请求操作 ( setCompletionBlockWithSuccess:failure:
)注册一个完成回调。