iOS25 大文件下载 文件输出流

大文件下载

使用NSURLConnection代理方式实现
// 接收到响应的时候:创建一个空的文件

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{   
 // 获取文件长度
    self.movieCount = [response.allHeaderFields[@"Content-Length"] integerValue];  
   // 创建一个空文件
    [[NSFileManager defaultManager] createFileAtPath:SLQFilePath contents:nil attributes:nil];    
   // 创建文件句柄
    self.handle = [NSFileHandle fileHandleForWritingAtPath:SLQFilePath];
 }
// 接收到具体数据:马上把数据写入一开始创建好的文件
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{  
  // 移动到文件末尾
    [self.handle seekToEndOfFile];   
 // 写入数据
    [self.handle writeData:data]; 
    self.currentCount += data.length;    
 CGFloat progress = 1.0 * self.currentCount / self.movieCount;   
  self.progressView.progress = progress;   
   NSLog(@"%f",progress * 100 );
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{    self.movieCount = 0;   
    // 关闭文件
    [self.handle closeFile];  
      self.handle = nil;}
NSOutputStream

文件流,文件输出流,可以输出到内存、硬盘、NSData
- (void)viewDidLoad {
    [super viewDidLoad];   
 // 建立连接
    NSURL *url  = [NSURL URLWithString:@"http://123.123.123.123/resources/videos/minion_02.mp4"];
    [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url] delegate:self];
}
 /**
 * 接收到响应的时候:创建一个空的文件
 */
 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{    
 // 获取服务器那里给出的建议名字   response.suggestedFilename);
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];   
  // 创建文件流
    self.stream = [[NSOutputStream alloc] initToFileAtPath:path append:YES];   
   // 打开文件流
    [self.stream open];
}
   /**
 * 接收到具体数据:马上把数据写入一开始创建好的文件
 */
   - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{    
   // 参数1要求是bytes
    [self.stream write:[data bytes]  maxLength:data.length];   
    NSLog(@"---");
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{   
     // 关闭文件流
    [self.stream close];
}
原文地址:https://www.cnblogs.com/ytmaylover/p/5065867.html