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

布局如下:


iOS中 断点下载详解 韩俊强的博客_第1张图片

基本拖拉属性:

#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;
}

最终效果如下:

iOS中 断点下载详解 韩俊强的博客_第2张图片

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


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



你可能感兴趣的:(ios,断点下载,ios开发,韩俊强的博客,iOS断点下载)