iOS开发系列-文件下载
小文件下载
NSURLConnection下载小文件
#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDataDelegate>
/** 记录文件的总大小 */
@property (nonatomic, assign) long long totalSize;
/** 下载的文件名 */
@property (nonatomic, strong) NSString *fileName;
/** 已经下载的data */
@property (nonatomic, strong) NSMutableData *downLoadData;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_04.mp4"];
NSURLRequest *rquest = [NSURLRequest requestWithURL:url];
// 发送请求
[NSURLConnection connectionWithRequest:rquest delegate:self];
}
#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpRespone = (NSHTTPURLResponse *)response;
_totalSize = httpRespone.expectedContentLength; // 获取下载文件的总大小
_fileName = httpRespone.suggestedFilename; // 下载文件的名
NSLog(@"%@", httpRespone);
// 获取响应头字段的value
// NSString *contentLength = httpRespone.allHeaderFields[@"Content-Length"]; // 也可以获取文件的总长度
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// 拼接NSData
[self.downLoadData appendData:data];
// 计算进度
NSUInteger currLength = self.downLoadData.length;
double progress = (currLength * 1.0 / self.totalSize) * 100;
NSLog(@"------------------%@", [NSString stringWithFormat:@"%.2f%%", progress]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// 下载完成将下载的Data写入沙河
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
NSString *filePath = [path stringByAppendingPathComponent:self.fileName];
[self.downLoadData writeToFile:filePath options:kNilOptions error:nil];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
@end
NSURLSession下载小文件
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:@"http://img.zcool.cn/community/0142135541fe180000019ae9b8cf86.jpg@1280w_1l_2o_100sh.png"];
// 创建session
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString *filePath = [FMFILE stringByAppendingPathComponent:response.suggestedFilename];
[[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:nil];
}];
// 执行task
[task resume];
}
NSURLSessionDownloadTask下载完文件后自动将文件临时存储在沙盒的tmp目录下,通过Block的location返回。我们需要将tmp目录下的文件剪切到要存储的目录下否则系统自动清理。
这里注意:[NSURL fileURLWithPath:filePath]返回的URL是带有协议头的,而[NSURL URLWithString:@""];返回的是不带协议头的URL。
因此开发中建议使用NSURLSessionDownloadTask下载小文件。
大文件下载
NSURLConnection下载大文件
大文件的下载不能像小文件下载的方式将服务器每次返回的data拼接到内存。而是需要边下载边写进沙盒,这里需要使用NSFileHander这个类。
#import "ViewController.h"
#define FMFILE NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject
@interface ViewController ()<NSURLConnectionDataDelegate>
/** 记录文件的总大小 */
@property (nonatomic, assign) long long totalLength;
/** 当前总长度 */
@property (nonatomic, assign) long long currLength;
@property (nonatomic, strong) NSFileHandle *handle;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_04.mp4"];
NSURLRequest *rquest = [NSURLRequest requestWithURL:url];
// 发送请求
[NSURLConnection connectionWithRequest:rquest delegate:self];
}
#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// 下载完成将下载的Data写入沙河
NSHTTPURLResponse *httpRespone = (NSHTTPURLResponse *)response;
NSString *fileName = httpRespone.suggestedFilename; // 下载文件的名
NSString *filePath = [FMFILE stringByAppendingPathComponent:fileName];
// 接收到一个响应创建空的文件
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
self.totalLength = httpRespone.expectedContentLength; // 获取下载文件的总大小
self.handle = [NSFileHandle fileHandleForWritingAtPath:filePath];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// 每次文件从文件内容尾部拼接
[self.handle seekToEndOfFile];
// 开始写入数据
[self.handle writeData:data];
// 拼接总长度
self.currLength += data.length;
// 计算当前进度
CGFloat progress = self.currLength * 1.0 / self.totalLength;
NSLog(@"下载进度----%.2f%%", progress *100);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self.handle closeFile];
self.handle = nil;
// 清零数据
self.currLength = 0;
self.totalLength = 0;
}
@end
NSURLSession下载大文件
#import "ViewController.h"
#define FMFILE NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject
@interface ViewController ()<NSURLSessionDownloadDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_04.mp4"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
[task resume];
}
#pragma mark - NSURLSessionDataDelegate
/*
每当写入数据到临时文件就会调用该方法
bytesWritten 这次写入数据的长度
totalBytesWritten 已经写入的文件长度
totalBytesExpectedToWrite 要下载文件的中长度
*/
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
CGFloat progress = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
NSLog(@"----------%.2f%%", progress*100);
}
/*
恢复下载
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
}
// 现在完毕
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
NSString *filePath = [FMFILE stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
// 剪切文件
[[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:nil];
}
// 完成跟失败都会来到这个代理方法
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"------------%s", __func__);
}
@end
NSURLSession断点下载大文件
NSURLSession创建的Task的的父类NSURLSessionTask有三个方法,因此它的子类都有这些方法。我们就可以利用这几个方法做断点下载。
- (void)suspend;
- (void)resume;
- (void)cancel;
iOS开发系列-文件下载的更多相关文章
- iOS开发系列--网络开发
概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博.微信等,这些应用本身可能采用iOS开发,但是所有的数据支撑都是基于后台网络服务器的.如今,网络编程越来越普遍,孤立的应用通常是没有生命力 ...
- iOS开发系列--Swift语言
概述 Swift是苹果2014年推出的全新的编程语言,它继承了C语言.ObjC的特性,且克服了C语言的兼容性问题.Swift发展过程中不仅保留了ObjC很多语法特性,它也借鉴了多种现代化语言的特点,在 ...
- iOS开发系列文章(持续更新……)
iOS开发系列的文章,内容循序渐进,包含C语言.ObjC.iOS开发以及日后要写的游戏开发和Swift编程几部分内容.文章会持续更新,希望大家多多关注,如果文章对你有帮助请点赞支持,多谢! 为了方便大 ...
- iOS开发系列--App扩展开发
概述 从iOS 8 开始Apple引入了扩展(Extension)用于增强系统应用服务和应用之间的交互.它的出现让自定义键盘.系统分享集成等这些依靠系统服务的开发变成了可能.WWDC 2016上众多更 ...
- iOS开发系列--Swift进阶
概述 上一篇文章<iOS开发系列--Swift语言>中对Swift的语法特点以及它和C.ObjC等其他语言的用法区别进行了介绍.当然,这只是Swift的入门基础,但是仅仅了解这些对于使用S ...
- iOS开发系列--通知与消息机制
概述 在多数移动应用中任何时候都只能有一个应用程序处于活跃状态,如果其他应用此刻发生了一些用户感兴趣的那么通过通知机制就可以告诉用户此时发生的事情.iOS中通知机制又叫消息机制,其包括两类:一类是本地 ...
- iOS开发系列--数据存取
概览 在iOS开发中数据存储的方式可以归纳为两类:一类是存储为文件,另一类是存储到数据库.例如前面IOS开发系列-Objective-C之Foundation框架的文章中提到归档.plist文件存储, ...
- iOS开发系列--C语言之基础知识
概览 当前移动开发的趋势已经势不可挡,这个系列希望浅谈一下个人对IOS开发的一些见解,这个IOS系列计划从几个角度去说IOS开发: C语言 OC基础 IOS开发(iphone/ipad) Swift ...
- iOS开发系列--让你的应用“动”起来
--iOS核心动画 概览 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌.在这里你可以看到iOS中如何使用图层精简非交互式绘图,如何通过核心动画创建 ...
随机推荐
- Android中onTouch方法的执行过程以及和onClick执行发生冲突的解决办法
$*********************************************************************************************$ 博主推荐 ...
- 树形dp换根,求切断任意边形成的两个子树的直径——hdu6686
换根dp就是先任取一点为根,预处理出一些信息,然后在第二次dfs过程中进行状态的转移处理 本题难点在于任意割断一条边,求出剩下两棵子树的直径: 设割断的边为(u,v),设down[v]为以v为根的子树 ...
- vue webpack打包后.css文件里面的背景图片路径错误解决方法
资源相对引用路径 问题描述 一般情况下,通过webpack+vuecli默认打包的css.js等资源,路径都是绝对的. 但当部署到带有文件夹的项目中,这种绝对路径就会出现问题,因为把配置的static ...
- flutter 显示HTML代码
需求是后台返回的是富文本,所以需要吧富文本转成flutter 能识别的内容 找了几个插件只有这个比较好用写下来 dependencies: flutter_html: ^0.9.8 安装 下剩下的就比 ...
- 2019/11/8 CSP模拟
T1 药品实验 内网#4803 由概率定义,有\[a + b + c = 0\] 变形得到\[1 - b = a + c\] 根据题意有\[p_i = a p _{i - 1} + b p_i + c ...
- LightOJ-1282-Leading and Trailing-快速幂+数学
You are given two integers: n and k, your task is to find the most significant three digits, and lea ...
- bagging和boosting以及rand-forest
bagging: 让该学习算法训练多轮,每轮的训练集由从初始的训练集中随机取出的n个训练样本组成,某个初始训练样本在某轮训练集中可以出现多次或根本不出现,训练之后可得到一个预测函数序列h_1,⋯ ⋯h ...
- 将sparkStreaming结果保存到Redshift数据库
1.保存到redshift数据库的代码 package test05 import org.apache.log4j.{Level, Logger}import org.apache.spark.rd ...
- JS对象 JavaScript 中的所有事物都是对象,如:字符串、数值、数组、函数等,每个对象带有属性和方法。
什么是对象 JavaScript 中的所有事物都是对象,如:字符串.数值.数组.函数等,每个对象带有属性和方法. 对象的属性:反映该对象某些特定的性质的,如:字符串的长度.图像的长宽等: 对象的方法: ...
- Android开发 了解ViewModel
前言 ViewModel是google推出的一个数据处理框架,ViewModel类是被设计用来以可感知生命周期的方式存储和管理 UI 相关数据ViewModel中数据会一直存活即使 activity ...