【问题标题】:Need help to download files asynchronously getting progress using AFnetworking需要帮助以使用 AFnetworking 异步下载文件以获得进度
【发布时间】:2015-03-25 15:44:20
【问题描述】:

我正在尝试使用 AFNetworking 2.0 (https://github.com/AFNetworking/AFNetworking) 创建 iPhone 文件下载器

我在这段代码中遇到了随机问题:

-(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" -> 所以下载是成功的,但是程序告诉我们有问题

Error Domain=NSPOSIXErrorDomain Code=13 "The operation could not be completed. Permission denied" -> SO NOTHING IS DOWNLOADED,而且大多数情况下都会发生这种情况。

我在网上找不到与这些问题相关的任何内容,这真的很烦人,因为它是随机发生的。

感谢您的帮助,祝您有美好的一天。

【问题讨论】:

标签: ios objective-c afnetworking-2


【解决方案1】:

我的第一印象是您错误地检索文档目录。

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];

【讨论】:

    猜你喜欢
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    相关资源
    最近更新 更多