网络编程归纳总结六阶段
HEAD请求
不获取响应体,只获取响应头
一般在下载之前先获取文件的大小
NSURLResponse 的属性
MIMEType
返回的文件的类型 Content-Type
expectedContentLength
文件的预期大小(实际大小)
suggestedFilename
建议保存的文件的名字
代码示例:异步请求
输出的data是空的
nil、NULL、NSNULL的区别
同步发送请求的方法参数中的**
参数传地址,可以让方法返回多个值。
方法内部会把传过来的数据复制一份重新赋值
如果想修改外部调用的时候对应变量的值,应该传地址,直接修改地址中的数据
演示求数组中的最大值,最小值
传对象的时候
- (void)test:(NSString **)str{
*str = [NSString stringWithFormat:@"abc %d",123];
}
NULL和nil的区别
error:(NSError **)error 传空的时候NULL
NULL C语言的,空地址,地址为0
nil OC的空对象,栈上开辟空间,指向内存为0的堆地址
NSNull 目的是为数组和字典赋空值
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setObject:[NSNull null] forKey:@"abc"];
NSURLConnection下载
下载文件
没有下载进度提示
内存会瞬间暴涨(如果下载的文件特别大,程序会闪退)。
代码:
HMDownloader *downloader = [[HMDownloader alloc] init];
NSLog(@"start");
[downloader download:@"http://192.168.31.244/ooxx.mp4"];
- (void)download:(NSString *)urlStr{
NSURL *url = [NSURL URLWithString:str];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//
[data writeToFile:@"/Users/xxxxx/Desktop/444.mp4" atomically:YES];
NSLog(@"over");
}];
}
NSURLConnectionDownloadDelegate
使用NSURLConnection的代理方法下载,可以一点一点下载文件,解决内存瞬间暴涨的问题
代理NSURLConnectionDownloadDelegate
此代理专门用来处理报刊杂志的下载,下载完成看不到文件
设置代理
//设置connection的代理
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
//开始
[conn start];
代理方法
//下载进度
- (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes{
NSLog(@"%f", totalBytesWritten*1.0f / expectedTotalBytes);
}
//下载完成
- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL{
NSLog(@"下载完成--%@",destinationURL);
}
//下载出错
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"错误");
}
NSURLConnectionDataDelegate
NSURLConnectionDataDelegate中的方法
可以获取下载进度
内存不暴涨
保存文件还没有实现
//接收到响应头
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
//通过响应头获取文件的大小
NSLog(@"%lld",response.expectedContentLength);
self.expectedContentLength = response.expectedContentLength;
}
//持续接收数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
self.currentFileSize += data.length;
NSLog(@"%f",self.currentFileSize*1.0f/self.expectedContentLength);
}
//下载完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"over");
}
//下载出错
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"错误");
}
保存文件
定义属性,记录当前下载的二进制文件内容 懒加载
//文件的二进制数据
@property (nonatomic, strong) NSMutableData *currentData;
持续接收数据的时候保存数据
[self.currentData appendData:data];
下载完成后保存文件
[self.currentData writeToFile:@"/Users/xxxxxx/Desktop/xxoo.mp4" atomically:YES];
问题:使用这个内存会暴涨
解决内存暴涨
保存文件时,解决内存暴涨
原因:把每次下载的二进制数据,累加到内存中
解决:每次接收到二进制文件数据后,直接保存到文件
保存文件的类
NSFileHandle (读写二进制文件)
NSOutputStream
NSFileManager (创建 删除 复制文件)
NSFileHandle
- (void)writeToFile:(NSData *)data{
//NSFileManager 负责文件的 删除、复制、是否存在等操作
//NSFileHandle 负责对文件的处理
NSString *path = @"/Users/xxxxx/Desktop/4444.mp4";
//创建文件句柄
NSFileHandle *file = [NSFileHandle fileHandleForWritingAtPath:path];
//如果文件不存在file == nil
if (file == nil) {
//直接把data写入文件
[data writeToFile:path atomically:YES];
}else{
//把文件指针移动到文件末尾
[file seekToEndOfFile];
//把文件指针移动到指定位置
// [file seekToFileOffset:<#(unsigned long long)#>]
//写入文件
[file writeData:data];
//关闭文件句柄
[file closeFile];
}
}
NSOutputStream
NSStream 流 抽象类
- (void)open;
- (void)close;
NSOutputStream 输出流
在内存和硬盘之间创建一个管道,运送一些字节
把字节通过流写入文件
- (NSInteger)write:(const uint8_t *)buffer maxLength:(NSUInteger)len;
示例:
下载完响应头
//初始化流
NSString *path = @"/Users/xxxxx/Desktop/4444.mp4";
self.stream = [NSOutputStream outputStreamToFileAtPath:path append:YES];
//打开流 如果文件不存在会自动创建文件
[self.stream open];
下载结束或下载出错,关闭流
下载的过程中,写入文件
强调内容 [self.stream write:data.bytes maxLength:data.length];
问题:
如果文件已经存在,再次下载的时候会追加文件
在文件下载之前,先判断时候有文件,如果则删除重新下载
删除文件,如果文件不存在,此代码什么都不会执行
[[NSFileManager defaultManager] removeItemAtPath:path error:NULL];
最近才开始往github上放东西 在公司写的又不能放= = 大家姑且看看吧
github地址: https://github.com/FuThD