布局如下:

基本拖拉属性:

#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. Mac Webview OC与JS交互实现

    1.首先,需要定义一个JS可识别的变量(如external)用于OC与JS交互 - (void)webView:(WebView *)sender didClearWindowObject:(WebS ...

  2. Mysql优化--Show Profile

    Mysql 系列文章主页 =============== 是Mysql提供可以用来分析当前会话中语句执行的资源消耗情况.可以用于Sql的调优的测量.默认情况下处于关闭状态,并保存最近 15 次的运行结 ...

  3. Mysql锁机制--间隙锁的危害

    Mysql 系列文章主页 =============== 1 准备数据 1.1 建表 DROP TABLE IF EXISTS employee; CREATE TABLE IF NOT EXISTS ...

  4. 学习笔记:Zookeeper选举机制

    1.Zookeeper选举机制 Zookeeper虽然在配置文件中并没有指定master和slave 但是,zookeeper工作时,是有一个节点为leader,其他则为follower Leader ...

  5. 新浪微博Oauth2.0授权认证及SDK、API的使用(Android)

    ---------------------------------------------------------------------------------------------- [版权申明 ...

  6. GirlFriendNotFoundException异常是怎样处理的?

    GirlFriendNotFoundException异常是怎样处理的? 如果说要去创造这个异常,那么我们的JAVA程序里,肯定是继承Exception去处理,所有我们可以先实现一个自己的Except ...

  7. Ubuntu等Linux系统显卡性能测试软件 Unigine 3D

    Ubuntu等Linux系统显卡性能测试软件 Unigine 3D Ubuntu Intel显卡驱动安装,请参考: http://blog.csdn.net/zhangrelay/article/de ...

  8. bmp格式图像的读写函数(对一个开源代码的封装)

    在网上看到一段读写bmp格式图像的代码,本文对这段代码分成两个函数封装起来方便使用,一个函数是读取bmp格式的图像,一个是向指定文件写入bmp格式的图像. 前提 我们不需要知道这段代码是如何读取bmp ...

  9. SpriteKit塔防游戏动态改变防御塔价格标签的颜色

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 本篇blog在DinoDefense塔防游戏基础之上做一处小的 ...

  10. Java并发框架——AQS中断的支持

    线程的定义给我们提供了并发执行多个任务的方式,大多数情况下我们会让每个任务都自行执行结束,这样能保证事务的一致性,但是有时我们希望在任务执行中取消任务,使线程停止.在java中要让线程安全.快速.可靠 ...