大文件断点下载

NSURLConnection实现大文件下载

2014-12-08 20:30:41http://blog.csdn.net/itcontend/article/details/41795641--点击数:19

NSURLConnection实现大文件下载

1.方案:利用NSURLConnection和它的代理方法

1>发送一个请求// 1.URLNSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos.zip"

];

// 2.请求

NSURLRequest *request = [NSURLRequest requestWithURL:url];

// 3.下载(创建完conn对象后,会自动发起一个异步请求)[NSURLConnection connectionWithRequest:request delegate:self

];

2>在代理方法中处理服务器返回的数据

/**

在接收到服务器的响应时: 1.创建一个空的文件 2.用一个句柄对象关联这个空的文件,目的是:方便后面用句柄对象往文件后面写数据 */- (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:

nilattributes: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;

}

/**

在所有数据接收完毕时,关闭句柄对象 */- (void

)connectionDidFinishLoading:(NSURLConnection *)connection

{

self.currentLength=0

;

self.totalLength=0;   //关闭文件    [self

.writeHandle closeFile];

self.writeHandle =nil

;

}

注意:千万不能用NSMutableData来拼接服务器返回的数据


你可能感兴趣的:(大文件断点下载)