gpt4 book ai didi

objective-c - 使用 afnetworking 下载文件之前获取文件大小

转载 作者:行者123 更新时间:2023-12-03 17:10:45 26 4
gpt4 key购买 nike

我有一个问题,我想获取我放入文本字​​段中的链接的文件大小,并在开始下载之前将其显示在标签中。我做了一些事情,并且使用 [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];

最佳答案

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

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

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

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

关于objective-c - 使用 afnetworking 下载文件之前获取文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30411703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com