AFNetworking - 使用AFHTTPRequestOperation下载文件?

Bat*_*ard 16 afnetworking

男人,难倒在这一个.尝试使用AFNetworking下载文件,我能做的最好的事情是捕获downloadProgressBlock中的进度字节.我已经尝试了许多不同的AFNetworking分叉,现在我又回到了最新版本.看起来曾经AFHTTPRequestOperation被修改为也包括NSURLResponse但在最新版本中已经消失了.并且,根据下面的代码,永远不会调用"成功"块.我得到下载字节的日志,然后调用^ complete.从未调用成功与错误.

对此的任何指导都很棒.我无法弄清楚返回数据的位置以及如何让它使用NSFileManager?我需要下载文件,而不是为图像写入流等.

编辑:我还尝试通过覆盖 - (void)连接捕获数据:didReceiveData,如文档中所建议的那样,但没有做任何事情.

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

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];
Run Code Online (Sandbox Code Playgroud)

Car*_*rdo 64

您可以简单地使用AFNetworking中包含的此功能,甚至将其保存到磁盘 - 请注意operation.outputStream:

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
}];
Run Code Online (Sandbox Code Playgroud)

编辑:missed

[operation start]; 
Run Code Online (Sandbox Code Playgroud)

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

// [apiClient enqueueHTTPRequestOperation:operation];
Run Code Online (Sandbox Code Playgroud)

  • 有人给这个人一个upvote!OP应该选择答案! (3认同)