iOS技术文档No.25 Foundation_NSByteCountFormatter下载速度

个别时候我们可能需要知道我们当前的网络速度是多少,例如我们在下载的时候,NSByteCountFormatter是系统提供给我们的转换字节的一个类,可以配合我们常用的第三方AFNetworking来计算网速

NSByteCountFormatter转换字节的方法
+ (NSString *)stringFromByteCount:(long long)byteCount countStyle:(NSByteCountFormatterCountStyle)countStyle;

代码

需要定义一个下载对象:DownTask。DownTask需要有的属性:lastRead(记录一秒前的数据)、speed(速度)、date(记录上一秒计算之后的时间)。注意:这里的一秒不是严格意义上的一秒,有可能大于一秒,我们计算的是平均速度,所以不会误差太大。

下载中代码:
//构造资源链接
    NSString *urlString = @"http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    //创建AFN的manager对象
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
    //构造URL对象
    NSURL *url = [NSURL URLWithString:urlString];
    //构造request对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    
    DownTask *down = [[DownTask alloc]init];
    //获取当前时间
    NSDate *currentDate = [NSDate date];
    down.date=currentDate;//开始时间
    //使用系统类创建downLoad Task对象
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"下载进度---%lld---%lld", downloadProgress.completedUnitCount,downloadProgress.totalUnitCount);//下载进度
        //获取当前时间
        NSDate *currentDate = [NSDate date];
        //当前时间和上一秒时间做对比,大于等于一秒就去计算
        if ([currentDate timeIntervalSinceDate:down.date] >= 1) {
            //时间差
            double time = [currentDate timeIntervalSinceDate:down.date];
            //计算速度
            long long speed = (downloadProgress.completedUnitCount-down.lastRead)/time;
            //把速度转成KB或M
            down.speed = [down formatByteCount:speed];
            //维护变量,将计算过的清零
            down.lastRead = downloadProgress.completedUnitCount;
            //维护变量,记录这次计算的时间
            down.date = currentDate;
            NSLog(@"下载速度---%@",down.speed);
        }
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //返回下载到哪里(返回值是一个路径)
        //拼接存放路径
        NSURL *pathURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
        return [pathURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        //下载完成走这个block
        if (!error)
        {
            //如果请求没有错误(请求成功), 则打印地址
            NSLog(@"%@", filePath);
        }
    }];
    
    //开始请求
    [task resume];

DownTask代码:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface DownTask : NSObject
@property (nonatomic,assign)NSUInteger lastRead;//记录一秒前的数据
@property (nonatomic,copy)NSString *speed;//速度
@property (nonatomic,strong)NSDate *date;//记录上一秒计算之后的时间

- (NSString*)formatByteCount:(long long)size;
@end
#import "DownTask.h"

@implementation DownTask
- (NSString*)formatByteCount:(long long)size
{
    return [NSByteCountFormatter stringFromByteCount:size countStyle:NSByteCountFormatterCountStyleFile];
}
@end

实际测试时由于我找的资源太小了,下载的太快,大家可以找个大点的资源或者想办法给电脑限速了试试

下载速度.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,819评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,837评论 18 139
  • 肥胖是一种以身体脂肪含量过多和/或分布异常,常伴有体质量增加为重要特征的、多病因的、能够并发多种疾患的慢性...
    沃筱蝶阅读 594评论 0 0
  • 概要 在大数据量高并发访问时,经常会出现服务或接口面对暴涨的请求而不可用的情况,甚至引发连锁反映导致整个系统崩溃。...
    jijs阅读 3,748评论 1 53
  • 能源与绿色 新型绿化挑战 不同于历史上的任何时期,如今建筑行业建筑美学与技术因素的临界点。一方面,这些可见因素都处...
    门门门门呀阅读 258评论 0 0