AF断点下载和计算下载速度


AFHTTPRequestOperation *operation;//成员变量


- (void)startDownload {

    DownTask *downTask = [[DownTask alloc]init];

    downTask.date = [NSDate date];

    NSString *strURL = [self.dic[@"url"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSString *downloadUrl = FORMAT(@"%@%@",url_down,strURL);

    NSArray * arr = [self.dic[@"url"] componentsSeparatedByString:@"/"];

    NSString * str = [arr objectAtIndex:(arr.count - 1)];

    [MagicBeanDefaults setMapFileName:str];

    NSString *downloadPath = [[[CacheManager sharedManager]getCacheUrl] stringByAppendingPathComponent:str];

    request = [NSURLRequest requestWithURL:[NSURL URLWithString:downloadUrl]];

    //检查文件是否已经下载了一部分

    unsigned long long downloadedBytes = 0;

    if ([[NSFileManager defaultManager] fileExistsAtPath:downloadPath]) {

        //获取已下载的文件长度

        downloadedBytes = [self fileSizeForPath:downloadPath];

        if (downloadedBytes > 0) {

            NSMutableURLRequest *mutableURLRequest = [request mutableCopy];

            NSString *requestRange = FORMAT(@"bytes=%llu-", downloadedBytes);

            [mutableURLRequest setValue:requestRange forHTTPHeaderField:@"Range"];

            request = mutableURLRequest;

        }

    }

    operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:downloadPath append:YES];

    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

        float progress = (float)(totalBytesRead + downloadedBytes) / (totalBytesExpectedToRead + downloadedBytes);

        unsigned long long downloaded = [self fileSizeForPath:downloadPath]/1024/1024;

        NSString *downStr = FORMAT(@"%llu",downloaded);

        //计算一秒中的速度

        downTask.totalRead += bytesRead;

        //获取当前时间

        NSDate *currentDate = [NSDate date];

        //当前时间和上一秒时间做对比,大于等于一秒就去计算

        if ([currentDate timeIntervalSinceDate:downTask.date] >= 1) {

            //时间差

            double time = [currentDate timeIntervalSinceDate:downTask.date];

            

            if(downTask.totalRead == 0)

            {

                downTask.speed = @"0KB/s";

            }else

            {

                long long speed = downTask.totalRead/time;

                downTask.speed = [downTask formatByteCount:speed];

            }

            

            //维护变量,将计算过的清零

            downTask.totalRead = 0.0;

            //维护变量,记录这次计算的时间

            downTask.date = currentDate;

        }

        NSLog(@"%f------%@Mb",progress,downStr);

        NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:FORMAT(@"%f",progress),@"progress",downStr,@"downloaded",downTask.speed,@"speed", nil];

        [[NSNotificationCenter defaultCenter]postNotificationName:@"MAPDownloadProgress" object:dic];

    }];

    //成功和失败回调

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        [btn setTitle:NSLocalizedString(@"SyncNOw", nil) forState:UIControlStateNormal];

        _isDownloading = NO;

        [MagicBeanDefaults setMapDown:YES];

        NSString *md5Str = [MD5 getFileMD5WithPath:FORMAT(@"%@/%@",[[CacheManager sharedManager]getCacheUrl],str)];

        if ([md5Str isEqualToString:self.dic[@"md5"]]) {

            

        }else{

            [[NSFileManager defaultManager] removeItemAtPath:FORMAT(@"%@/%@",[[CacheManager sharedManager]getCacheUrl],[MagicBeanDefaults getMapFileName]) error:nil];

            [MagicBeanDefaults setMapDown:NO];

            [MagicBeanDefaults setMapFileName:nil];

//            [MagicBeanDefaults setMapDownInfo:nil];

            [UIView markToast:@"下载文件出错,请重新下载。"];

        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [UIView markToast:NSLocalizedString(@"DownloadFailed", nil)];

        _isDownloading = NO;

    }];

    [operation start];

}


//用于计算文件下载速度

#import <Foundation/Foundation.h>


@interface DownTask : NSObject


@property (nonatomic,assign) NSUInteger totalRead;


@property (nonatomic,strong)NSDate *date;


@property (nonatomic,strong)NSString * speed;


- (NSString*)formatByteCount:(long long)size;


@end



#import "DownTask.h"


@implementation DownTask


- (NSString *)formatByteCount:(long long)size

{

    return [NSByteCountFormatter stringFromByteCount:size countStyle:NSByteCountFormatterCountStyleFile];

}


@end


//用于计算文件的md5值和服务器对比

+(NSString*)getFileMD5WithPath:(NSString*)path

{

    return (__bridge_transfer NSString *)FileMD5HashCreateWithPath((__bridge CFStringRef)path, FileHashDefaultChunkSizeForReadingData);

}







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值