文件下载 NSURLConnection——小文件下载

1.下载小文件,只适合几百k,1、2M的文件

//1.设置网址
//2.加载请求
//3.设置代理
//4.实现代理方法下载文件
 NSURL *url = [NSURL URLWithString:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1492791082124&di=fc642407b4ec19430334653a9b873cff&imgtype=0&src=http%3A%2F%2Fi0.szhomeimg.com%2FUploadFiles%2FBBS%2F2006%2F10%2F24%2F27567833_1950.442.jpg"];
 NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
代理实现
#pragma mark ---NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"下载失败%@",error);
}
//下载响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
//获取文件大小
    _totalSize = response.expectedContentLength;
}
//下载数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    //拼接数据
    [_mudata appendData:data];
    //获取当前进度
    NSLog(@"%f",1.0*_mudata.length/_totalSize);
}
//下载完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

    NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"1.jpg"];
    [_mudata writeToFile:fullPath atomically:YES];
}

  

  缺点:[_mudata appendData:data],会使内存暴涨,而且下载完毕后内存不会下降

2.通过句柄来下载大文件

#pragma mark ----------------------
#pragma mark NSURLConnectionDataDelegate
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"didReceiveResponse");

    //1.得到文件的总大小(本次请求的文件数据的总大小)
    self.totalSize = response.expectedContentLength;

    //2.写数据到沙盒中
    self.fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"123.mp4"];

    //3.创建一个空的文件
    [[NSFileManager defaultManager] createFileAtPath:self.fullPath contents:nil attributes:nil];

    //4.创建文件句柄(指针)
    self.handle = [NSFileHandle fileHandleForWritingAtPath:self.fullPath];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //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)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //1.关闭文件句柄
    [self.handle closeFile];
    self.handle = nil;
    NSLog(@"connectionDidFinishLoading");
    NSLog(@"%@",self.fullPath);
}

 3.通过断点续传来下载大文件

设置请求头,如果文件存在就继续下载

同上
    //2.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSString *range = [NSString stringWithFormat:@"bytes=%zd-",self.currentSize];
    [request setValue:range forHTTPHeaderField:@"Range"];
    //同上
}
#pragma mark ----------------------
#pragma mark NSURLConnectionDataDelegate
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //1.得到文件的总大小(本次请求的文件数据的总大小)
    self.totalSize = response.expectedContentLength+self.currentSize;
    if (self.currentSize > 0) {
        return;
    }
    //同上
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //同上
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //同上
}

 缺点:下次运行工程进来就要重新下载  

时间: 2024-10-22 17:57:42

文件下载 NSURLConnection——小文件下载的相关文章

ios开发网络学习三:NSURLConnection小文件大文件下载

一:小文件下载 #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> /** 注释 */ @property (nonatomic, strong) NSMutableData *fileData; @property (nonatomic, assign) NSInteger totalSize; @property (weak, nonatomic) IB

文件下载(NSURLConnection/NSURLSession)

最基本的网络文件下载(使用原生的网络请求) #pragma mark - 小文件下载 // 方法一: NSData dataWithContentsOfURL - (void)downloadFile1 { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // 其实这就是一个GET请求 NSURL *url = [NSURL URLWithString:@"http://localh

小文件下载

简单介绍两种小文件下载的方法 - (void)downloadFile { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // 其实这就是一个GET请求 NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/images/minion_01.png"]; NSData *d

源码0602-06-掌握-小文件下载-大文件下载

// // ViewController.m // 06-掌握-小文件下载 #import "ViewController.h" @interface ViewController () <NSURLConnectionDataDelegate> @property (weak, nonatomic) IBOutlet UIProgressView *progressView; /** 文件数据 */ @property (nonatomic, strong) NSMuta

2016 - 1 - 23 小文件下载

一: 使用NSData直接下载: // 这种方法没法暂停,只适合下载小文件 NSURL *url = [[NSURL alloc] initWithString:@"http://120.25.226.186:32812/resources/images/minion_15.png" ]; NSData *data = [NSData dataWithContentsOfURL:url options:kNilOptions error:nil]; UIImage *image = [

NSURLConnection 大文件下载

#import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> @property (weak, nonatomic) IBOutlet UIProgressView *progressView; @property (nonatomic, assign) NSInteger totalSize; @property (nonatomic, assign) NSInte

iOS之小文件下载

#import "ViewController.h" @interface ViewController () <NSURLConnectionDataDelegate> @property (weak, nonatomic) IBOutlet UIProgressView *progressView; /** 文件数据 */ @property (nonatomic, strong) NSMutableData *fileData; /** 文件的总长度 */ @prop

tar_ssh 配合提高小文件下载效率

scp传小文件时会由于每个文件确认等待,一方面等待确认时tcp窗口无法填满,另一方面文件传完之前也不会开始读下一个文件.而tar ssh配合则恰好解决该问题.当然大文件传输也不会有作用,甚至还会变慢. #不带压缩ssh ${username}@${ip} '(cd ${src_folder_path}&&tar -cf - ${src_folder_name} | cat)' | tar xfv - -C ${dst_path}#带压缩ssh ${username}@${ip} '(cd

php文件下载(解决文件下载后多几个字节的问题) 与封装成类的例子

php文件下载比较常见,网上的资料比较多,在此不再强调怎么去实现(因为也是网上看的).下面主要说明的是下载代码的注意点. php下载文件主要是把文件以字节流直接输出,也就是echo fread($file, filesize($file_name));,这里要注意的是如果你在代码之前(或之后)有输出,也可能被写入下载的文件中,解决的方法是使用 ob_start();和ob_end_clean();来清除前面的输出,后面的输出直接使用@fclose($file);exit(0);来解决. 代码如下