使用AFHTTPRequest下载文件操作不起作用?

时间:2012-11-18 01:45:58

标签: objective-c download nsurlrequest

这是我正在使用的代码(from this Stack Overflow question,虽然它略有修改):

NSLog(@"Saving File...");

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[detailDataSourceDict valueForKey:@"filepath"]]];
NSLog(@"This is the link you are downloading: %@",request);
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Successfully downloaded file to %@", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

[operation start];

我得到NSLog“已成功下载文件到/ Users / xxxx / Library / Application Support / iPhone Simulator / 6.0 / Applications / F29C1E99-A277-41DC-8205-6556B6123A85 / Documents”但当我在Finder中打开该文件夹时,我没看到文件。有什么我做错了吗?我的代码中没有错误。任何帮助将不胜感激,谢谢。


更新

我正在使用AFNetwork库......

1 个答案:

答案 0 :(得分:1)

您将下载位置设置为实际的文档目录,而不是目录中的文件。更新代码以使用目录中的特定文件。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0]; //filepath to documents directory!
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:[path stringByAppendingPathComponent:@"filename.extension"] append:NO];

此外,我认为您可能希望设置inputStream属性而不是outputStream,因为您正在下载文件而不是上传文件。