iOS之大文件下载(NSURLConnection)
2016-04-04 16:05
423 查看
#import "ViewController.h" #define File [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"minion_15.mp4"] @interface ViewController () <NSURLConnectionDataDelegate> @property (weak, nonatomic) IBOutlet UIProgressView *progressView; /** 文件的总长度 */ @property (nonatomic, assign) NSInteger contentLength; /** 当前下载的总长度 */ @property (nonatomic, assign) NSInteger currentLength; /** 文件句柄对象 */ @property (nonatomic, strong) NSFileHandle *handle; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_15.mp4"]; [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url] delegate:self]; } #pragma mark - <NSURLConnectionDataDelegate> /** * 接收到响应的时候:创建一个空的文件 */ - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response { // 获得文件的总长度 self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue]; // 创建一个空的文件 [[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]; // 拼接总长度 self.currentLength += data.length; // 进度 self.progressView.progress = 1.0 * self.currentLength / self.contentLength; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // 关闭handle [self.handle closeFile]; self.handle = nil; // 清空长度 self.currentLength = 0; } @end
相关文章推荐
- iOS之小文件下载
- iOS项目依赖注入简介
- iOS高仿城觅-感谢大神分享
- IOS响应式编程框架ReactiveCocoa(RAC)使用示例-备
- ios内存优化的轮播图
- IOS-二维码
- iOS自定义转场动画(下)
- iOS开发中对info.plist文件的解读
- IOS-内存分析
- IOS-MBProgressHUD常见的几种用法
- iOS自定义转场动画(上)
- iOS之摇一摇功能实现
- iOS之原生二维码扫描
- iOS之使用ZbarSDK实现扫描二维码以及条形码功能
- IOS-社会化分享
- ios 之重写 -init方法
- ios基础之initialze与load
- iOS开发传VC的方法
- iOS开发中XIB的使用
- IOS开发之免费证书+不越狱真机调试