iOS-网络-NSURLConnection实现文件下载
2018-03-05 17:15
295 查看
一.一般方法
// ViewController.m
#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDataDelegate>
/** 注释 */
@property (nonatomic, strong) NSMutableData *fileData;
@property (nonatomic, assign) NSInteger totalSize;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation ViewController
-(NSMutableData *)fileData
{
if (_fileData == nil) {
_fileData = [NSMutableData data];
}
return _fileData;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self download3];
}
//耗时操作[NSData dataWithContentsOfURL:url]
-(void)download1
{
//1.url
NSURL *url = [NSURL URLWithString:@"http://img5.imgtn.bdimg.com/it/u=1915764121,2488815998&fm=21&gp=0.jpg"];
//2.下载二进制数据
NSData *data = [NSData dataWithContentsOfURL:url];
//3.转换
UIImage *image = [UIImage imageWithData:data];
}
//1.无法监听进度
//2.内存飙升
-(void)download2
{
//1.url
// NSURL *url = [NSURL URLWithString:@"http://imgsrc.baidu.com/forum/w%3D580/sign=54a8cc6f728b4710ce2ffdc4f3cec3b2/d143ad4bd11373f06c0b5bd1a40f4bfbfbed0443.jpg"];
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];
//2.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//4.转换
// UIImage *image = [UIImage imageWithData:data];
//
// self.imageView.image = image;
//NSLog(@"%@",connectionError);
//4.写数据到沙盒中
NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"123.mp4"];
[data writeToFile:fullPath atomically:YES];
}];
}
//内存飙升
-(void)download3
{
//1.url
// NSURL *url = [NSURL URLWithString:@"http://imgsrc.baidu.com/forum/w%3D580/sign=54a8cc6f728b4710ce2ffdc4f3cec3b2/d143ad4bd11373f06c0b5bd1a40f4bfbfbed0443.jpg"];
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];
//2.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.发送请求
[[NSURLConnection alloc]initWithRequest:request delegate:self];
}
#pragma mark ----------------------
#pragma mark NSURLConnectionDataDelegate
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"didReceiveResponse");
//得到文件的总大小(本次请求的文件数据的总大小)
self.totalSize = response.expectedContentLength;
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// NSLog(@"%zd",data.length);
[self.fileData appendData:data];
//进度=已经下载/文件的总大小
NSLog(@"%f",1.0 * self.fileData.length /self.totalSize);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connectionDidFinishLoading");
//4.写数据到沙盒中
NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"123.mp4"];
[self.fileData writeToFile:fullPath atomically:YES];
NSLog(@"%@",fullPath);
}
@end
二.大文件断点下载,NSFileHandle,NSOutputStream
// ViewController.m
#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDataDelegate>
/** 注释 */
@property (nonatomic, strong) NSMutableData *fileData;
@property (nonatomic, assign) NSInteger totalSize;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation ViewController
-(NSMutableData *)fileData
{
if (_fileData == nil) {
_fileData = [NSMutableData data];
}
return _fileData;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self download3];
}
//耗时操作[NSData dataWithContentsOfURL:url]
-(void)download1
{
//1.url
NSURL *url = [NSURL URLWithString:@"http://img5.imgtn.bdimg.com/it/u=1915764121,2488815998&fm=21&gp=0.jpg"];
//2.下载二进制数据
NSData *data = [NSData dataWithContentsOfURL:url];
//3.转换
UIImage *image = [UIImage imageWithData:data];
}
//1.无法监听进度
//2.内存飙升
-(void)download2
{
//1.url
// NSURL *url = [NSURL URLWithString:@"http://imgsrc.baidu.com/forum/w%3D580/sign=54a8cc6f728b4710ce2ffdc4f3cec3b2/d143ad4bd11373f06c0b5bd1a40f4bfbfbed0443.jpg"];
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];
//2.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//4.转换
// UIImage *image = [UIImage imageWithData:data];
//
// self.imageView.image = image;
//NSLog(@"%@",connectionError);
//4.写数据到沙盒中
NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"123.mp4"];
[data writeToFile:fullPath atomically:YES];
}];
}
//内存飙升
-(void)download3
{
//1.url
// NSURL *url = [NSURL URLWithString:@"http://imgsrc.baidu.com/forum/w%3D580/sign=54a8cc6f728b4710ce2ffdc4f3cec3b2/d143ad4bd11373f06c0b5bd1a40f4bfbfbed0443.jpg"];
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];
//2.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.发送请求
[[NSURLConnection alloc]initWithRequest:request delegate:self];
}
#pragma mark ----------------------
#pragma mark NSURLConnectionDataDelegate
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"didReceiveResponse");
//得到文件的总大小(本次请求的文件数据的总大小)
self.totalSize = response.expectedContentLength;
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// NSLog(@"%zd",data.length);
[self.fileData appendData:data];
//进度=已经下载/文件的总大小
NSLog(@"%f",1.0 * self.fileData.length /self.totalSize);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connectionDidFinishLoading");
//4.写数据到沙盒中
NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"123.mp4"];
[self.fileData writeToFile:fullPath atomically:YES];
NSLog(@"%@",fullPath);
}
@end
二.大文件断点下载,NSFileHandle,NSOutputStream
// ViewController.m // 08-掌握-小文件下载 #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> @property (weak, nonatomic) IBOutlet UIProgressView *progressView; @property (nonatomic, assign) NSInteger totalSize; @property (nonatomic, assign) NSInteger currentSize; /** 沙盒路径 */ @property (nonatomic, strong) NSString *fullPath; /** 连接对象 */ @property (nonatomic, strong) NSURLConnection *connect; /** 输出流*/ @property (nonatomic, strong) NSOutputStream *stream; /** 文件句柄*/ //@property (nonatomic, strong)NSFileHandle *handle; @end @implementation ViewController - (IBAction)startBtnClick:(id)sender { [self download]; } - (IBAction)cancelBtnClick:(id)sender { [self.connect cancel]; } - (IBAction)goOnBtnClick:(id)sender { [self download]; } //内存飙升 -(void)download { //1.url // NSURL *url = [NSURL URLWithString:@"http://imgsrc.baidu.com/forum/w%3D580/sign=54a8cc6f728b4710ce2ffdc4f3cec3b2/d143ad4bd11373f06c0b5bd1a40f4bfbfbed0443.jpg"]; NSURL *url = [NSURL URLWithString:@"http://www.33lc.com/article/UploadPic/2012-10/2012102514201759594.jpg"]; //2.创建请求对象 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //设置请求头信息,告诉服务器值请求一部分数据range /* bytes=0-100 bytes=-100 bytes=0- 请求100之后的所有数据 */ NSString *range = [NSString stringWithFormat:@"bytes=%zd-",self.currentSize]; [request setValue:range forHTTPHeaderField:@"Range"]; NSLog(@"+++++++%@",range); //3.发送请求 NSURLConnection *connect = [[NSURLConnection alloc]initWithRequest:request delegate:self]; self.connect = connect; } #pragma mark ---------------------- #pragma mark NSURLConnectionDataDelegate -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"didReceiveResponse"); //1.得到文件的总大小(本次请求的文件数据的总大小 != 文件的总大小) // self.totalSize = response.expectedContentLength + self.currentSize; if (self.currentSize >0) { return; } self.totalSize = response.expectedContentLength; //2.写数据到沙盒中 self.fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"123.jpg"]; NSLog(@"%@",self.fullPath); //3.创建输出流 // NSOutputStream // NSInputStream /* 第一个参数:文件的路径 第二个参数:YES 追加 特点:如果该输出流指向的地址没有文件,那么会自动创建一个空的文件 */ NSOutputStream *stream = [[NSOutputStream alloc]initToFileAtPath:self.fullPath append:YES]; //打开输出流 [stream open]; self.stream = stream; // //使用文件句柄 // //3.创建一个空的文件 // [[NSFileManager defaultManager] createFileAtPath:self.fullPath contents:nil attributes:nil]; // //4.创建文件句柄(指针) // self.handle = [NSFileHandle fileHandleForWritingAtPath:self.fullPath]; // } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { //写数据 [self.stream write:data.bytes maxLength:data.length]; // //1.移动文件句柄到数据的末尾 // [self.handle seekToEndOfFile]; // //2.写数据 // [self.handle writeData:data]; //3.获得进度 self.currentSize += data.length; //进度=已经下载/文件的总大小 NSLog(@"%f",1.0 * self.currentSize/self.totalSize); self.progressView.progress = 1.0 * self.currentSize/self.totalSize; //NSLog(@"%@",self.fullPath); } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { //关闭流 [self.stream close]; self.stream = nil; // //1.关闭文件句柄 // [self.handle closeFile]; // self.handle = nil; NSLog(@"connectionDidFinishLoading"); NSLog(@"%@",self.fullPath); } @end
相关文章推荐
- iOS开发之网络编程--使用NSURLConnection实现大文件断点续传下载+使用输出流代替文件句柄
- iOS开发之网络编程--使用NSURLConnection实现大文件断点续传下载
- iOS开发之网络编程--使用NSURLConnection实现大文件断点续传下载+使用输出流代替文件句柄
- iOS开发之网络编程--使用NSURLConnection实现大文件断点续传下载+使用输出流代替文件句柄
- iOS开发之网络编程--使用NSURLConnection实现大文件断点续传下载
- iOS开发之网络编程--使用NSURLConnection实现大文件下载
- iOS开发之网络编程--4、NSURLSessionDataTask实现文件下载(离线断点续传下载) <进度值显示优化>
- iOS开发之网络编程--4、NSURLSessionDataTask实现文件下载(离线断点续传下载) <进度值显示优化>
- iOS开发之网络编程--4、NSURLSessionDataTask实现文件下载(离线断点续传下载) <进度值显示优化>
- iOS开发网络篇―实现大文件的多线程断点下载
- iOS开发之网络编程--使用NSURLConnection实现文件上传
- iOS-网络-NSURLConnection实现文件的上传
- iOS-网络-NSURLSessionDataTask实现大文件下载,进度提示
- iOS网络-通过NSURLConnection文件下载,断点下载,输出流下载
- ios开发网络学习九:NSURLSessionDownloadTask实现大文件下载
- ios开发网络学习十:利用文件句柄实现大文件下载
- iOS开发之网络编程--3、NSURLSessionDataTask实现文件下载(离线断点续传下载)
- iOS NSURLSession 实现网络请求-文件下载-上传-后台下载
- ios开发网络学习四:NSURLConnection大文件断点下载
- iOS网络开发(8)文件下载的实现