简单粗暴直接上代码
#import "ViewController.h"
@interface ViewController () <NSURLConnectionDataDelegate]] >
/** 从服务器接收到的数据 */
@property (nonatomic, strong) NSMutableData *receiveData;
/** 要下载文件的总长度 */
@property(nonatomic,assign) long long expectedContentLength;
/** 当前已经下载的字节数 */
@property(nonatomic,assign) long long currentLength;
@end
@implementation ViewController
/**
问题:
1. 没有进度
2. 会有瞬间的内存峰值
NSURLConnection已经有10多年历史,异步方法是从iOS 4.0开始才有的,
在此之前都是通过"代理"方式来实现网络连接,获取二进制数据的
问题分析:之所以出现内存峰值,是因为用了临时数据拼接所有的二进制数据,意味着要下载多大的文件,就会占用多大的内存
解决方法:每接收到一个数据包,就写入一次文件
*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 1. url
NSString *urlString = @"http://192.168.32.2/11-Vim简单演练.mp4";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
// 2. request
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3. 网络连接异步方法
// [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//
// // 将视频文件保存到桌面
// [data writeToFile:@"/Users/apple/Desktop/123.mp4" atomically:YES];
// }];
// 传统的代理方式
// 实例化连接对象
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
// 启动连接
[connection start];
}
#pragma mark - 网络连接代理方法
// 1. 接收到服务器的响应,服务器会告诉客户端,有关请求资源的一些信息
// URL 客户端请求的资源路径
// *** MIMEType 服务器告诉客户端,应该用什么软件可以打开二进制数据,例如Flash,需要安装插件之后才能够看到
// 之所以能够丰富多彩,是因为有足够多的软件能够打开不同的二进制数据
// expectedContentLength 期望的内容长度,通常对于下载来说,就是要下载的文件长度
// textEncodingName 文本编码名称,对于html,text其他格式的文本文件,可以知道用什么软件打开,并使用对应的编码
// suggestedFilename 建议的文件名
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"服务器响应");
self.receiveData = [[NSMutableData alloc] init];
// A. 记录住要下载文件的总长度
self.expectedContentLength = response.expectedContentLength;
self.currentLength = 0;
}
// 2. 接收到服务器的二进制数据,有可能会多次
// 追加每次获得的数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// 追加数据
[self.receiveData appendData:data];
// B. 可以根据下载数据的长度,计算已经下载的长度,能够知道百分比
self.currentLength += data.length;
// 计算百分比
float progress = (float)self.currentLength / self.expectedContentLength;
NSLog(@"%f", progress);
}
// 3. 请求加载完成,一次请求的所有资源全部获取完成
// 将最终的数据写入磁盘
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"加载完成");
// 将数据写入磁盘
[self.receiveData writeToFile:@"/Users/apple/Desktop/aa.mp4" atomically:YES];
// 释放内存
self.receiveData = nil;
}
// 4. 提示:在开发网络应用,千万不要忘记出错处理!出现错误一定要及时通知用户
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"发生错误 %@", error);
}