iOS中 断点下载详解 韩俊强的博客

布局如下:



基本拖拉属性:

#import "ViewController.h"
#import "AFNetworking.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UILabel *progressLabel;

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@property (nonatomic, strong) AFHTTPRequestOperation *operation;

@end

@implementation ViewController



调用:

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    
    NSString *txtPath = [cachePath stringByAppendingPathComponent:@"mvTemp/mv.txt"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:txtPath]) {
        self.progressView.progress = [[NSString stringWithContentsOfFile:txtPath encoding:NSUTF8StringEncoding error:nil] floatValue];
        self.progressLabel.text = [NSString stringWithFormat:@"%.2f%%", _progressView.progress * 100];
        
    } else {
        self.progressView.progress = 0;
        self.progressLabel.text = @"0%";
    }
    NSLog(@"%@", NSHomeDirectory());
    
}

点击事件:

- (IBAction)startOrCancelDownLoad:(UIButton *)sender
{
    if ([sender.currentTitle isEqualToString:@"开始下载"]) {
        [sender setTitle:@"暂停下载" forState:UIControlStateNormal];
        
       
        NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        NSString *filePath = [cachePath stringByAppendingPathComponent:@"mv"];
        NSString *tempPath = [cachePath stringByAppendingPathComponent:@"mvTemp"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:filePath]) {
            [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        if (![fileManager fileExistsAtPath:tempPath]) {
            [fileManager createDirectoryAtPath:tempPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        NSString *mp4TempPath = [tempPath stringByAppendingPathComponent:@"mv.temp"];
        NSString *txtTempPath = [tempPath stringByAppendingPathComponent:@"mv.txt"];
        NSString *mp4Path = [filePath stringByAppendingPathComponent:@"mv.mp4"];
        NSURL *url = [NSURL URLWithString:@"http://video.szzhangchu.com/1442395443772_5176326090.mp4"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        unsigned long long downLoadBytes = 0;
        if ([fileManager fileExistsAtPath:mp4TempPath]) {
            downLoadBytes = [self fileSizeAtPath:mp4TempPath];
            NSString *range = [NSString stringWithFormat:@"bytes=%llu-", downLoadBytes];
            NSMutableURLRequest *mutableRequest = [request mutableCopy];
            [mutableRequest setValue:range forHTTPHeaderField:@"Range"];
            request = mutableRequest;
        }
        if (![fileManager fileExistsAtPath:mp4Path]) {
            self.operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
            [self.operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:mp4TempPath append:YES]];
            __weak typeof(self) weakSelf = self;
            [_operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                weakSelf.progressView.progress = (float)(totalBytesRead + downLoadBytes) / (float)(totalBytesExpectedToRead + downLoadBytes);
                weakSelf.progressLabel.text = [NSString stringWithFormat:@"%.2f%%", weakSelf.progressView.progress * 100];
                NSString *progress = [NSString stringWithFormat:@"%.3f", weakSelf.progressView.progress];
                [progress writeToFile:txtTempPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
                
            }];
            
            [_operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                [fileManager moveItemAtPath:mp4TempPath toPath:mp4Path error:nil];
                [fileManager removeItemAtPath:txtTempPath error:nil];
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
            }];
            
            [_operation start];
        }
        
    } else {
        [sender setTitle:@"开始下载" forState:UIControlStateNormal];
        [self.operation cancel];
        _operation = nil;
    }
    
    
    
}

- (unsigned long long)fileSizeAtPath:(NSString *)path
{
    unsigned long long fileSize = 0;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSError *error = nil;
        NSDictionary *dict = [fileManager attributesOfItemAtPath:path error:&error];
        if (dict && !error) {
            fileSize = [dict fileSize];
        }
    }
    return fileSize;
}

最终效果如下:


用到的第三方数据请求:AFNetworking,大家应该都有,这里不做介绍


关注博主微博每日更新技术:http://weibo.com/hanjunqiang



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

韩俊强

奖励一杯咖啡☕️

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值