布局如下:

基本拖拉属性:

#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

iOS中 断点下载详解 韩俊强的博客的更多相关文章

  1. iOS中 扫描二维码/生成二维码详解 韩俊强的博客

    最近大家总是问我有没有关于二维码的demo,为了满足大家的需求,特此研究了一番,希望能帮到大家! 每日更新关注:http://weibo.com/hanjunqiang  新浪微博 指示根视图: se ...

  2. iOS中 HTTP/Socket/TCP/IP通信协议详解 韩俊强的博客

    每日更新关注:http://weibo.com/hanjunqiang  新浪微博 简单介绍: // OSI(开放式系统互联), 由ISO(国际化标准组织)制定 // 1. 应用层 // 2. 表示层 ...

  3. iOS中 本地通知/本地通知详解 韩俊强的博客

    布局如下:(重点讲本地通知) iOS开发者交流QQ群: 446310206 每日更新关注:http://weibo.com/hanjunqiang  新浪微博 Notification是智能手机应用编 ...

  4. iOS中 最新支付宝支付(AliPay) 韩俊强的博客

    每日更新关注:http://weibo.com/hanjunqiang  新浪微博 现在的支付方式一般有三种, 支付宝, 微信, 网银. 个人觉得最简单易用的还是支付宝, 微信虽然看起来币支付宝要简单 ...

  5. iOS中 CoreGraphics快速绘图(详解) 韩俊强的博客

    每日更新关注:http://weibo.com/hanjunqiang  新浪微博 第一步:先科普一下基础知识: Core Graphics是基于C的API,可以用于一切绘图操作 Core Graph ...

  6. iOS中 最新微信支付/最全的微信支付教程详解 韩俊强的博客

    每日更新关注:http://weibo.com/hanjunqiang  新浪微博! 亲们, 首先让我们来看一下微信支付的流程吧. 1. 注册微信开放平台,创建应用获取appid,appSecret, ...

  7. iOS中 语音识别功能/语音转文字教程详解 韩俊强的博客

    每日更新关注:http://weibo.com/hanjunqiang  新浪微博 原文地址:http://blog.csdn.net/qq_31810357/article/details/5111 ...

  8. iOS中 蓝牙2.0详解/ios蓝牙设备详解 韩俊强的博客

    每日更新关注:http://weibo.com/hanjunqiang  新浪微博 整体布局如下:     程序结构如右图: 每日更新关注:http://weibo.com/hanjunqiang  ...

  9. iOS中 百度地图详解 韩俊强的博文

    需要准备工作按照下图引进类库 需要添加 添加的两个字符串为:NSLocationWhenInUseUsageDescription  /  NSLocationAlwaysUsageDescripti ...

随机推荐

  1. Linux学习之CentOS(十五)----磁盘管理之 启动挂载(转)

    启动挂载 /etc/fstab 及 /etc/mtab 刚刚上面说了许多,那么可不可以在启动的时候就将我要的文件系统都挂好呢?这样我就不需要每次进入 Linux 系统都还要在挂载一次呀!当然可以啰!那 ...

  2. Docker安装tomcat和部署项目

    随着微服务的流行,Docker越来越流行,正如它的理念"Build, Ship, and Run Any App, Anywhere"一样,Docker提供的容器隔离技术使得开发人 ...

  3. 批量录入快递地址-快宝地址服务(PHP代码示例)

    快递地址写错了怎么办?快递地址写的不详细怎么办?怎么皮批量录入收件人地址?微商怎么批量录入发件人地址?快宝地址清洗,有效的解决了寄送快递时,批量录入收件人信息.发件人信息时,纠正地址数据,不完整地址识 ...

  4. net框架运行原理

    核心是CLR(通用语言运行时), c#或者其它各种语言编译原理:将原代码通过相对的编译器(语法检查原代码分析)生成IL代码托管(IL也称托管代码),最后得到一个托管模块,一个或多个托管模块组成程序集( ...

  5. ORA-01207: file is more recent than control file - old control file的处理方法

    1. 连接数据库 sqlplus / as sysdba2. 启动数据库,此时会报标题中的错误startup 3.备份创建控制文件的脚本语句,并从中拷贝出相关的NORESETLOGS模式的创建控制文件 ...

  6. LinkedList源码和并发问题分析

    1.LinkedList源码分析 LinkedList的是基于链表实现的java集合类,通过index插入到指定位置的时候使用LinkedList效率要比ArrayList高,以下源码分析是基于JDK ...

  7. Git-gitblit-Tortoisegit 搭建Windows Git本地服务器

    1.Gitblit安装 1.1.Gitblit简介 Git在版本控制领域可谓是深受程序员喜爱.对于开源的项目,可以免费托管到GitHub上面,相当的方便.但是私有项目托管到GitHub会收取相当昂贵的 ...

  8. 深入了解Java虚拟机和内存管理

    1.java程序的执行过程      java源文件->解析器->class文件->java类加载器->java运行时数据区->执行引擎 2.我们接下来看一下java运行 ...

  9. Jmeter(六)_前置处理器

     BeanShell PreProcessor  使用BeanShell在请求进行之前进行操作.语法使用与BeanShell Sampler是一样的.但可使用的内置变量稍有不同 参考示例 Jmeter ...

  10. Docker rancher 部署

    Docker-rancher #环境 centos7.4 , Docker version 17.12.0-ce #下载docker镜像 docker pull mysql:5.7 docker pu ...