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
iOS中 断点下载详解 韩俊强的博客的更多相关文章
- iOS中 扫描二维码/生成二维码详解 韩俊强的博客
最近大家总是问我有没有关于二维码的demo,为了满足大家的需求,特此研究了一番,希望能帮到大家! 每日更新关注:http://weibo.com/hanjunqiang 新浪微博 指示根视图: se ...
- iOS中 HTTP/Socket/TCP/IP通信协议详解 韩俊强的博客
每日更新关注:http://weibo.com/hanjunqiang 新浪微博 简单介绍: // OSI(开放式系统互联), 由ISO(国际化标准组织)制定 // 1. 应用层 // 2. 表示层 ...
- iOS中 本地通知/本地通知详解 韩俊强的博客
布局如下:(重点讲本地通知) iOS开发者交流QQ群: 446310206 每日更新关注:http://weibo.com/hanjunqiang 新浪微博 Notification是智能手机应用编 ...
- iOS中 最新支付宝支付(AliPay) 韩俊强的博客
每日更新关注:http://weibo.com/hanjunqiang 新浪微博 现在的支付方式一般有三种, 支付宝, 微信, 网银. 个人觉得最简单易用的还是支付宝, 微信虽然看起来币支付宝要简单 ...
- iOS中 CoreGraphics快速绘图(详解) 韩俊强的博客
每日更新关注:http://weibo.com/hanjunqiang 新浪微博 第一步:先科普一下基础知识: Core Graphics是基于C的API,可以用于一切绘图操作 Core Graph ...
- iOS中 最新微信支付/最全的微信支付教程详解 韩俊强的博客
每日更新关注:http://weibo.com/hanjunqiang 新浪微博! 亲们, 首先让我们来看一下微信支付的流程吧. 1. 注册微信开放平台,创建应用获取appid,appSecret, ...
- iOS中 语音识别功能/语音转文字教程详解 韩俊强的博客
每日更新关注:http://weibo.com/hanjunqiang 新浪微博 原文地址:http://blog.csdn.net/qq_31810357/article/details/5111 ...
- iOS中 蓝牙2.0详解/ios蓝牙设备详解 韩俊强的博客
每日更新关注:http://weibo.com/hanjunqiang 新浪微博 整体布局如下: 程序结构如右图: 每日更新关注:http://weibo.com/hanjunqiang ...
- iOS中 百度地图详解 韩俊强的博文
需要准备工作按照下图引进类库 需要添加 添加的两个字符串为:NSLocationWhenInUseUsageDescription / NSLocationAlwaysUsageDescripti ...
随机推荐
- 数组查找算法的C语言 实现-----线性查找和二分查找
线性查找 Linear Search 用户输入学生学号的成绩 二分查找 Binary Search 要求数据表是已经排好序的 程序存在小的瑕疵
- mongodb数据库备份迁移 windows -> linux
mongodb数据库备份迁移 windows -> linux cd 到本机mongodb的安装目录 如: C:\Program Files\MongoDB\Server\3.4\bin 可以发 ...
- random 模块
import stringprint (random.random()) # 0-1之间选浮点数print (random.randint(0,99,))#0-99之间选任意整数print (rand ...
- spark升级后 集成hbase-1.0.0-cdh5.4.5异常
.具体场景如下: spark1.6 升级 spark2.2 后 分析查询hbase 数据报异常: 具体错误如下: ERROR TableInputFormat: java.io ...
- 渗透测试环境DVWA搭建
一.DVWA介绍 DVWA(Damn Vulnerable Web Application)是一个用来进行安全脆弱性鉴定的PHP/MySQL Web应用,旨在为安全专业人员测试自己的专业技能和工具提供 ...
- vue.js-路由
1:编写router.js import Router from "vue-router" import Vue from "vue" import rou ...
- jQuery 遍历 – 过滤
缩小搜索元素的范围 三个最基本的过滤方法是:first(), last() 和 eq(),它们允许您基于其在一组元素中的位置来选择一个特定的元素. 其他过滤方法,比如 filter() 和 not() ...
- 2.docker常用命令
一.安装相关 #查看docker是否安装 rpm -q docker #CentOS下安装docker sudo yum install docker #启动 Docker systemctl s ...
- Bootstrap3 表单-被支持的控件:输入框
输入框包括大部分表单控件.文本输入域控件,还支持所有 HTML5 类型的输入控件: text.password.datetime.datetime-local.date.month.time.week ...
- MySQL之sql文件的导入导出
window下 1.导出整个数据库(无需登录mysql)mysqldump -u 用户名 -p 数据库名 > 导出的文件名mysqldump -u dbuser -p dbname > d ...