/** 创建一个句柄对象 */
@property(strong,nonatomic) NSFileHandle *handle;
#define file [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"xxx.txt"]
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [[NSURL alloc] initWithString:@"http://xxxx"];
[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url] delegate:self];
}
/**
* 开始接收收据时调用
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
// 创建一个空文件
[[NSFileManager defaultManager] createFileAtPath:file contents:nil attributes:nil];
// 句柄对象初始化
self.handle = [NSFileHandle fileHandleForWritingAtPath:file];
}
/**
* 一点一点接收数据
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
// 指定文件写入的位置为文件末尾处
[self.handle seekToEndOfFile];
// 写入数据
[self.handle writeData:data];
}
/**
* 数据接收完成后调用
*/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
// 关闭句柄对象
[self.handle closeFile];
self.handle = nil;
}