网络请求:
NSURLConnection
发送同步请求:
nsurlconnection发送同步请求是阻塞式,会阻塞当前线程
发送异步请求:
nsurlconnection发送异步请求底层是开启子线程发送请求,回调默认是在主线程中回调,如果需要在子线程中回调可以设置代理队列setDelegateQueue:子线程队列.
PS:请求大的响应数据时使用delegate方式更加适合
NSURLConnection与NSRunLoop
#import "ViewController.h"
@interface ViewController () <NSURLConnectionDataDelegate>
/** runLoop */
@property (nonatomic, assign) CFRunLoopRef runLoop;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 如果在子线程中使用NSURLConnection发送请求是不会有效果,因为子线程的runloop没有启动,子线程runloop默认是不启动的
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSURLConnection *conn = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com/images/234234324limgAB/2342lkjasdf3kkkkk.jpg"]] delegate:self];
// 决定代理方法在哪个队列中执行
[conn setDelegateQueue:[[NSOperationQueue alloc] init]];
// 启动子线程的runLoop
// [[NSRunLoop currentRunLoop] run];
// 保存当前runloop
self.runLoop = CFRunLoopGetCurrent();
// 启动runLoop
CFRunLoopRun();
});
}
#pragma mark - <NSURLConnectionDataDelegate>
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"didReceiveResponse******%@", [NSThread currentThread]);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"didReceiveData******%@", [NSThread currentThread]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connectionDidFinishLoading******%@", [NSThread currentThread]);
// 停止RunLoop
CFRunLoopStop(self.runLoop);
}
@end
NSURLSession
使用NSURLSession 对象创建Task,然后执行Task
Task的类型: NSURLSessionTask抽象类, 派生出子类有NSURLSessionDataTask,NSURLSesssionDownloadTask,NSURLSessionDataTask又派生出NSURLSessionUploadTask
NSURLSessionTask(抽象类)
- NSURLSessionDataTask
- NSURLSessionUploadTask
- NSURLSessionDownloadTask
文件上传:
文件解压缩:
ZipArchive框架
小文件写入:
NSData
大文件写入
NSFileHandle
NSOutPutStream