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中如何使用图层精简非交互式绘图,如何通过核心动画创建 ...
随机推荐
- csp-s模拟测试98
csp-s模拟测试98 $T1$??不是我吹我轻松手玩20*20.$T2$装鸭好像挺可做?$T3$性质数据挺多提示很明显? $One$ $Hour$ $Later$ 这$T1$什么傻逼题真$jb$难调 ...
- gnome/KDE安装,gnome出现问题,重新安装nvdia驱动, Linux(CentOS7) NVIDIA GeForece GTX 745 显卡驱动
新安装显示gtx745驱动NVIDIA-Linux-x86_64-346.59.run, yum groupremove kde-desktop yum groupinstall "Desk ...
- Centos7.5安装mysql 8.0.11
一.安装前准备 安装采用二进制包方式,软件包8.0.11版本下载地址: https://cdn.mysql.com//Downloads/MySQL-8.0/mysql-8.0.11-linux-gl ...
- DNS隧道--dnscat2
安装 服务端 git clone https://github.com/iagox86/dnscat2.git cd dnscat2 cd server sudo gem install bundle ...
- mysql 实现批量导入,并解决中文乱码问题
public static String url = "jdbc:mysql://ip/database?characterEncoding=UTF-8"; //在database ...
- elasticsearch的基本用法(转载)
本文出自:http://blog.csdn.net/feelig/article/details/8499614 最大的特点: 1. 数据库的 database, 就是 index 2. 数据库 ...
- C#& Screen 类&(&多&屏&幕&开&发)
原文:C#& Screen 类&(&多&屏&幕&开&发) Screen 类 下面的代码示例演示如何使用 Screen 类的各种方法和属性. 该示 ...
- 7.springboot+mybatis+redis整合
选择生成的依赖 选择保存的工程路径 查询已经生成的依赖,并修改mysql的版本 <dependencies> <dependency> <groupId>org.s ...
- BBS论坛 自定义form组件
二.自定义form组件 from django import forms from django.forms import widgets from app01 import models # 定制f ...
- 2019-7-27-解决从旧格式的-csproj-迁移到新格式的-csproj-格式-AssemblyInfo-文件值重复问题...
title author date CreateTime categories 解决从旧格式的 csproj 迁移到新格式的 csproj 格式 AssemblyInfo 文件值重复问题 lindex ...