0715大文件断点下载AF
1、用nsoutputstream实现文件下载 (02-nsoutputstream)
#import "ViewController.h"
@interface ViewController () <NSURLConnectionDataDelegate>
/** 输出流对象 */
@property (nonatomic, strong) NSOutputStream *stream;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]] delegate:self];
}
#pragma mark - <NSURLConnectionDataDelegate>
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// response.suggestedFilename : 服务器那边的文件名
// 文件路径
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];
NSLog(@"%@", file);
// 利用NSOutputStream往Path中写入数据(append为YES的话,每次写入都是追加到文件尾部)
self.stream = [[NSOutputStream alloc] initToFileAtPath:file append:YES];
// 打开流(如果文件不存在,会自动创建)
[self.stream open];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.stream write:[data bytes] maxLength:data.length];
NSLog(@"didReceiveData-------");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self.stream close];
NSLog(@"-------");
}
@end
2、NSURLConnection与Runloop的关联 (03-nsurlconnection与runloop)
用NSURLConnection发起的网络请求内部的机制是监听当前线程的runloop,有数据来就接收(以下载为例),所以如果放在子线程里发起一个NSURLConnection默认是无效的,因为子线程的runloop默认并没有启动
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSURLConnection *conn = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_01.png"]] delegate:self];
// 决定代理方法在哪个队列中执行
[conn setDelegateQueue:[[NSOperationQueue alloc] init]];
// 启动子线程的runLoop
[[NSRunLoop currentRunLoop] run];
});
3、如何停止一个runloop(03-nsurlconnection与runloop)
停止runloop只有用CFRunLoopStop(self.runLoop)
这个方法,而且此时启动方法也必须改为self.runLoop = CFRunLoopGetCurrent()
,最好用一个成员变量保存
4、NSURLSession在上传方面并不比NSURLConnection方便多少,而断点续传需要用socket来实现(需要服务器支持),而AFN上传封装后就方便多了(03-nsurlconnection与runloop)
5、AFN的注意点(12-afn03-解析服务器返回的数据)
设置返回的类型,默认是返回JSON
mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
// [AFHTTPResponseSerializer serializer]; 直接使用“服务器本来返回的数据”,不做任何解析(比如下载图片、视频、文件)
// [AFJSONResponseSerializer serializer]; // 解析服务器返回的JSON数据
// [AFXMLParserResponseSerializer serializer]; // 解析服务器返回的XML数据
6、Charles乱码解决办法
![](https://img.haomeiwen.com/i1477016/91898fe9d0bb23a6.png)
![](https://img.haomeiwen.com/i1477016/f39fefec06654718.png)
7、如何保证网络数据安全
- 方案一:对发送给服务器进行加密
- 方案二:使用https协议,App端什么都不用做,加密方案在服务器端
8、MD5(15-md5加密)
![](https://img.haomeiwen.com/i1477016/956f324d53dd17d9.png)
![](https://img.haomeiwen.com/i1477016/28ffe63e48777d62.png)
9、HTTPS简单介绍(16-https)
HTTPS= http + ssl,ssl就是服务器提供的要求客户端安装的证书,这个证书内部提供了公钥加密网络传输数据,而且只有服务器的私钥能进行解密,AFN框架内部已经实现了安装证书的代码,所以什么都不用做。
网友评论