首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >AFNetworking -使用AFHTTPRequestOperation下载文件?

AFNetworking -使用AFHTTPRequestOperation下载文件?
EN

Stack Overflow用户
提问于 2011-11-04 12:13:20
回答 1查看 24.7K关注 0票数 16

伙计,被这个难住了。尝试用AFNetworking下载一个文件,我能做的最多的就是捕获downloadProgressBlock中的进度字节。我已经尝试了许多不同的AFNetworking分支,现在我又回到了最新的版本。看起来AFHTTPRequestOperation一度被修改为包括NSURLResponse,但在最新版本中这一点已经消失了。而且,根据下面的代码,永远不会调用"success“块。我得到一个下载字节的日志,然后调用^complete。成功和错误永远不会被调用。

任何关于这方面的指导都会很棒。我不知道数据返回到哪里,以及如何让它对其使用NSFileManager?我需要下载文件,而不是为图像写流,等等。

编辑:我还尝试通过覆盖文档中建议的- (void)connection:didReceiveData来捕获数据,但没有做任何事情。

// url为http://mydomain.com/somezip.zip

代码语言:javascript
复制
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", url]]];

AFHTTPRequestOperation *operation = [AFHTTPRequestOperation HTTPRequestOperationWithRequest:request success:^(id object) {

    NSLog(@"hey, some success!");

} failure:^(NSHTTPURLResponse *response, NSError *error) {

    NSLog(@"%@", error);

}];


[operation setDownloadProgressBlock:^(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead) {

    // callback is sent in and works great.  Just outputting to the console at the moment
    SEL callme = NSSelectorFromString(callback);
    [sender performSelectorOnMainThread:callme withObject:[NSNumber numberWithInt:bytesRead] waitUntilDone:NO];

}];

[operation setCompletionBlock:^{
    NSLog(@"operation complete");
}];

NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-06-26 20:05:49

您可以简单地使用AFNetworking中包含的这一特性,甚至可以将其保存到磁盘上-请注意operation.outputStream

代码语言:javascript
复制
NSMutableURLRequest* rq = [api requestWithMethod:@"GET" path:@"YOUR/URL/TO/FILE" parameters:nil];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:rq] autorelease];

NSString* path=[@"/PATH/TO/APP" stringByAppendingPathComponent: imageNameToDisk];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSLog(@"SUCCCESSFULL IMG RETRIEVE to %@!",path)

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    // Deal with failure
}];

编辑missed

代码语言:javascript
复制
[operation start]; 

编辑...or if you use an AFHTTPClient * apiClient :

代码语言:javascript
复制
// [apiClient enqueueHTTPRequestOperation:operation];
票数 64
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8004808

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档