我正在尝试使用AFNetworking 2.0创建一个iPhone文件下载程序(https://github.com/AFNetworking/AFNetworking)
我得到这个代码的随机问题:
-(void)downloadFile:(NSString *)UrlAddress
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:UrlAddress]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSString *documentsDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *mp3Name = @"lol.mp3";
NSString *path = [NSString stringWithFormat:mp3Name,documentsDir];
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 setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
NSLog(@"Download = %f", (float)totalBytesRead / totalBytesExpectedToRead);
}];
[operation start];
}
当我调用这个函数时,我随机得到:
Successfully downloaded file to ...
->所以它在工作
Error Domain=NSURLErrorDomain Code=-1017 "cannot parse response"
->所以下载是成功的,但程序告诉我们有问题
错误域=NSPOSIXErrorDomain Code=13"操作无法完成。权限被拒绝"->所以没有下载任何内容,这种情况大多数时候都会发生。
我在网上找不到任何与这些问题有关的东西,这真的很烦人,因为它是随机发生的。
谢谢你的帮助,祝你今天愉快。
我的第一印象是检索文档目录不正确。
NSString *documentsDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *mp3Name = @"lol.mp3";
NSString *path = [NSString stringWithFormat:mp3Name,documentsDir];
如果查看此代码,路径将为:lol.mp3
由于这不是一个有效的路径,您的下载将失败。
应该这样做:
NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *mp3Name = @"lol.mp3";
NSString *path = [documentsDir stringByAppendingPathComponent:mp3Name];