小文件下载

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开发系列-文件下载的更多相关文章

  1. iOS开发系列--网络开发

    概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博.微信等,这些应用本身可能采用iOS开发,但是所有的数据支撑都是基于后台网络服务器的.如今,网络编程越来越普遍,孤立的应用通常是没有生命力 ...

  2. iOS开发系列--Swift语言

    概述 Swift是苹果2014年推出的全新的编程语言,它继承了C语言.ObjC的特性,且克服了C语言的兼容性问题.Swift发展过程中不仅保留了ObjC很多语法特性,它也借鉴了多种现代化语言的特点,在 ...

  3. iOS开发系列文章(持续更新……)

    iOS开发系列的文章,内容循序渐进,包含C语言.ObjC.iOS开发以及日后要写的游戏开发和Swift编程几部分内容.文章会持续更新,希望大家多多关注,如果文章对你有帮助请点赞支持,多谢! 为了方便大 ...

  4. iOS开发系列--App扩展开发

    概述 从iOS 8 开始Apple引入了扩展(Extension)用于增强系统应用服务和应用之间的交互.它的出现让自定义键盘.系统分享集成等这些依靠系统服务的开发变成了可能.WWDC 2016上众多更 ...

  5. iOS开发系列--Swift进阶

    概述 上一篇文章<iOS开发系列--Swift语言>中对Swift的语法特点以及它和C.ObjC等其他语言的用法区别进行了介绍.当然,这只是Swift的入门基础,但是仅仅了解这些对于使用S ...

  6. iOS开发系列--通知与消息机制

    概述 在多数移动应用中任何时候都只能有一个应用程序处于活跃状态,如果其他应用此刻发生了一些用户感兴趣的那么通过通知机制就可以告诉用户此时发生的事情.iOS中通知机制又叫消息机制,其包括两类:一类是本地 ...

  7. iOS开发系列--数据存取

    概览 在iOS开发中数据存储的方式可以归纳为两类:一类是存储为文件,另一类是存储到数据库.例如前面IOS开发系列-Objective-C之Foundation框架的文章中提到归档.plist文件存储, ...

  8. iOS开发系列--C语言之基础知识

    概览 当前移动开发的趋势已经势不可挡,这个系列希望浅谈一下个人对IOS开发的一些见解,这个IOS系列计划从几个角度去说IOS开发: C语言 OC基础 IOS开发(iphone/ipad) Swift ...

  9. iOS开发系列--让你的应用“动”起来

    --iOS核心动画 概览 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌.在这里你可以看到iOS中如何使用图层精简非交互式绘图,如何通过核心动画创建 ...

随机推荐

  1. Python pillow库安装报错

    报错信息: D:\pythontest\duanxinhongzha>pip3 install pillowCollecting pillow Could not find a version ...

  2. GDI+图像与GDI位图的相互转换

    Delphi的TBitmap封装了Windows的GDI位图,因此,TBitmap只支持bmp格式的图像,但是在Delphi应用程序中,常常会遇到图形格式的转换,如将Delphi位图TBitmap的图 ...

  3. 笨办法学Python记录--习题12-14 主要是pydoc用法,raw_input,argv

    20140413 -- 习题12 - 14 1. pydoc在windows的用法,必须进入到python安装目录,执行Python -m pydoc raw_input; 网上给出了一个好玩的,不过 ...

  4. MySql 5.6重新安装后忘记密码的解决办法

    1.先使用管理员权限的cmd停止MySQL服务:net stop mysql 2.重新打开一个cmd窗口进入安装目录的bin路径后输入mysqld --skip-grant-tables,注意这个cm ...

  5. Centos 6 & Centos 7安装rabbitmq3.6.15(单节点)

    系统准备 安装 erlang 语言环境 安装rabbitmq 配置网页插件 配置访问账号密码和权限 系统准备 centos6.5 与 centos7 都可以 ###安装依赖文件 yum -y inst ...

  6. Openstack nova-scheduler 源码分析 — Filters/Weighting

    目录 目录 前言 调度器 FilterScheduler调度器的工作流程 Filters 过滤器 Filters 类型 Weighting 权重 源码实现 关键文件及其意义 阶段一nova-sched ...

  7. Redis学习之缓存数据类型

    Redis缓存数据类型有5种,分别是String(字符串).List(列表).Hash(哈希).Set(无序,不重复集合).ZSet(sorted set:有序,不重复集合). String(字符串) ...

  8. Java多线程中提到的原子性和可见性、有序性

    1.原子性(Atomicity)   原子性是指在一个操作中就是cpu不可以在中途暂停然后再调度,既不被中断操作,要不执行完成,要不就不执行. 如果一个操作时原子性的,那么多线程并发的情况下,就不会出 ...

  9. haproxy Mycat集

    8-1   镜像haproxy docker run -it --privileged --name haproxy  docker.io/centos:latest 8-2wget http://w ...

  10. java_函数式编程写法

    package cn.aikang.Test; import org.junit.Test; import java.util.Scanner; import java.util.function.S ...