普通下载的情况,非Range方式请求的下载。
通过AFNetWorking获取文件的长度,代码简写如下
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:self.model.remoteUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[manager setDownloadTaskDidWriteDataBlock:^(NSURLSession * _Nonnull session, NSURLSessionDownloadTask * _Nonnull downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
}];
totalBytesExpectedToWrite即是想要的文件长度。但是这只是普通的获取文件的长度的方法,如果在请求的头文件中设置了Range,则该方法不起作用,该方法只返回设置Range的length。
通过头文件直接获取文件长度,遍访API没找到直接的获取文件真实长度的接口,既然没找到,那就手动获取吧。
我们获取的heads中的range内容如下
{contents = "bytes 0-10239/909216"}
数值909216既是我们想获得的文件的长度,单位为byte。如何获取呢?通过正则获取,写法如下
// 从head中获取filesize
- (NSInteger)getFileFromHead:(NSString *)contentRange {
- NSInteger fileSize = 0;
if (contentRange) {
NSError *error = NULL;
// 创建一个正则
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=/)[0-9]+$" options:NSRegularExpressionCaseInsensitive error:&error];
//仅取出第一条匹配记录
NSTextCheckingResult *firstResult = [regex firstMatchInString:contentRange options:0 range:NSMakeRange(0, [contentRange length])];
if (firstResult) {
fileSize = [[contentRange substringWithRange:firstResult.range] integerValue];
}
}
return fileSize;
}
我们在网络返回后就调用上面的正则函数获取文件长度,代码如下
destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)……
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSString *contentRange = [[(NSHTTPURLResponse *)response allHeaderFields] objectForKey:@"Content-Range"];
fileSize = [self getFileSizeFromHead:contentRange];
}
fileSize既是我们想要的文件长度值。