文件下载,获取下载速度

所谓的网络测速吧,之前的项目需要用到网络测速,没有找到合适的办法,通过下载文件来计算平均值也算是一个办法吧,哪位大神如果有更好的办法求分享:

里面使用的AFNetworking;先下载AFNetworking,导入头文件 :

#import "AFNetworking.h"

代码:

    _downButton = [UIButton buttonWithType:(UIButtonTypeRoundedRect)];

    _downButton.frame = CGRectMake(100, 100, 100, 30);

    [_downButton setTitle:@"测速" forState:(UIControlStateNormal)];

    [_downButton addTarget:self action:@selector(downButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];

    [self.view addSubview:_downButton];

 

-(void)downButtonAction:(UIButton * )button

{

    _timeTage = 0;

    NSLog(@"下载测试");

    NSString *urlStr = @"http://music.baidu.com/data/music/file?link=http://yinyueshiting.baidu.com/data2/music/124728882/73007331421179261128.mp3?xcode=6185914085043ea4dcd75b509939a523bf95b0c3b098821b&song_id=7300733";

    NSURL *url = [NSURL URLWithString:urlStr];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:3600];

    AFURLSessionManager * manager  = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    __autoreleasing NSProgress * progress = nil;

    

    _task = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {

        NSLog(@"开始下载");

        return nil;

    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {

        if (error) {

            NSLog(@"%@",error);

        }

    }];

    [_task resume];

    self.downProgress = progress;

    [self.downProgress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:nil];

    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(progressMethod:) userInfo:nil repeats:YES];

}

-(void)progressMethod:(id)sender

{  _timeTage ++;

    self.detailView.progress = self.downProgress.fractionCompleted;

    if (self.downProgress.fractionCompleted>=1) {

        [self.timer invalidate];//计时器停止

        CGFloat wangsu = 4096.0 / _timeTage ;

        _numberLable.text = [NSString stringWithFormat:@"平均网速:%.1lf K",wangsu];

    }

    NSLog(@"时间: %f",_timeTage);

}

//监听改变执行的方法

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{

    [self.detailView setProgress:self.downProgress.fractionCompleted];

    if (object == self.downProgress && [keyPath isEqualToString:@"fractionCompleted"] == YES) {

        CGFloat progressNumber  = self.downProgress.fractionCompleted;

        dispatch_queue_t queue = dispatch_get_main_queue();

        dispatch_async(queue, ^{

            self.numberLable.text = [NSString stringWithFormat:@"平均网速:%.1lf K",progressNumber * 1024];

        });

    }

}

注:本段代码中需要下载的文件为4M大小 :可以更换成自己的网址,不要下载太大的文件。

工作小记,欢迎共享
原文地址:https://www.cnblogs.com/fannyLi/p/4224081.html