数据下载存入沙河

   接收到服务器的响应就会调用

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

  // 获取沙河路径

    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

   // 拼接路径

   NSString *filepath = [caches stringByAppendingPathComponent:@"videos.zip"];

   // 创建一个空的文件 到 沙盒中

    NSFileManager *mgr = [NSFileManager defaultManager];

    [mgr createFileAtPath:filepath contents:nil attributes:nil]

 

// 创建一个用来写数据的文件句柄

    self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filepath];

  // 获得文件的总大小

    self.totalLength = response.expectedContentLength;

//写入数据

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    // 移动到文件的最后面

    [self.writeHandle seekToEndOfFile];

    

    // 将数据写入沙盒

    [self.writeHandle writeData:data];

    

    // 累计文件的长度

    self.currentLength += data.length;

    

    NSLog(@"下载进度:%f", (double)self.currentLength/ self.totalLength);

    self.circleView.progress = (double)self.currentLength/ self.totalLength;

}

 

/**

 *  3.加载完毕后调用(服务器的数据已经完全返回后)

 */

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    self.currentLength = 0;

    self.totalLength = 0;

    

    // 关闭文件

    [self.writeHandle closeFile];

    self.writeHandle = nil;

}

 

posted @ 2015-09-01 13:46  BN笨的很想飞  阅读(161)  评论(0)    收藏  举报