【问题标题】:Getting file size before downloading it using afnetworking在使用 afnetworking 下载文件之前获取文件大小
【发布时间】:2015-05-23 10:41:50
【问题描述】:

我有一个问题,我想在开始下载之前获取我放在文本字段中的链接的文件大小并在标签中显示它。 我做了几件事,我和[operation.response expectedContentLength] 我只得到 0。我在 .m 文件中的代码是这样的:

    NSString *fileName = [self.linkTextBox.stringValue lastPathComponent];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[self.linkTextBox stringValue]]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    NSLog(@"size :%lld", [operation.response expectedContentLength]);
    self.detailText.stringValue = [NSString stringWithFormat:@"%lld", [operation.response expectedContentLength]];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
      [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
      NSLog(@"bytesRead: %lu, totalBytesRead: %lld, totalBytesExpectedToRead: %lld", (unsigned long)bytesRead, totalBytesRead, totalBytesExpectedToRead);
}];
     [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation   *operation, id responseObject) {
            NSLog(@"Successfully downloaded file to %@", path);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error: %@", error);
        }];

        [operation start];

【问题讨论】:

  • 请 webdeveloper 给你尺寸...如果不下载,你无法获得尺寸
  • 预期长度可能为 0,因为服务器没有为您提供 Content-Length 标头。检查 HTTP 响应以查看它是否可用。
  • 我在开始下载时获得了总长度,但在开始之前它不可用。我的链接长度显示在其他下载管理器中,但不是我的

标签: objective-c cocoa afnetworking nsurl


【解决方案1】:

您可以发送 HEAD 请求而不是 GET 请求,这将要求服务器仅向您发送请求的标头。大多数服务器都支持此方法,当您想要获取有关您正在查询的实体的一些元数据信息时,它是首选方法,而无需下载它。

HEAD 请求可以通过创建NSMutableURLRequest 并设置HTTPMethod 属性来实现,如下所示:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:anURL];
request.HTTPMethod = @"HEAD";
// the rest of the code

这假设服务器开发人员完成了他的工作并且他期待HEAD 请求并且正在填充适当的 http 标头字段。

【讨论】:

  • 感谢您的回答,但现在我不明白您提供的解决方案是 void 类型,我真的不知道应该如何设置标签以显示 *request。
  • 我想我误解了你的问题,我以为你不想下载该文件。 @i_am_jorf 的解决方案应该更适合您,如果正如他和其他人所说,Content-Length http 标头由服务器正确发送。
【解决方案2】:

您无法在下载之前获得长度,但您可以在开始收到回复后立即获得。

您想使用setDownloadProgressBlock:,这是AFHTTPRequestOperation 的超类AFURLConnectionOperation 上的一个方法。回调有三个参数,第三个是totalBytesExpectedToRead

[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
    if (totalBytesExpectedToRead > 0) {
        // Do stuff...
    }
}];

正如其他人所说,如果服务器没有在 HTTP 响应中设置 content-length 标头,则该值可以为 0,因此请处理这种情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多