#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDataDelegate>
@end
@implementation ViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self newThreaddelegate2];
}
- (void)delegate1
{
//
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://api.apiopen.top/recommendPoetry"]];
//设置代理
//代理方法默认在主线程调用
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
//设置代理方法在哪个线程中调用
//开子线程:[[NSOperationQueue alloc] init]
//不能设置在主线程中执行[NSOperationQueue mainQueue],没有任何反应,不能这样设置
[connection setDelegateQueue:[[NSOperationQueue alloc] init]];
NSLog(@"+++++++++");
}
- (void)delegate2
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://api.apiopen.top/recommendPoetry"]];
//设置代理
//代理方法默认在主线程调用
//设置为立刻执行,跟delegate1没有区别
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
//设置代理方法在哪个线程中调用
[connection setDelegateQueue:[[NSOperationQueue alloc] init]];
//开始发送请求
[connection start];
NSLog(@"+++++++++");
}
//开子线程来发送请求
- (void)newThreaddelegate
{
//在子线程中发送请求代理方法可调用的条件是,开启runloop,模式为默认,缺一不可
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://api.apiopen.top/recommendPoetry"]];
//设置代理
//代理方法默认在主线程调用
//该方法内部会将connection对象作为一个source添加到runloop中,指定运行模式为默认
//由于是子线程,runloop没有开启,所以设置代理失败,代理方法不执行
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
//设置代理方法在哪个线程中调用
//开子线程:[[NSOperationQueue alloc] init]
//不能设置在主线程中执行[NSOperationQueue mainQueue],没有任何反应,不能这样设置
[connection setDelegateQueue:[[NSOperationQueue alloc] init]];
//让runloop开启
//设置了模式不是默认,也不行
// [[NSRunLoop currentRunLoop] runMode:UITrackingRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:1000]];
[[NSRunLoop currentRunLoop] run];
NSLog(@"newThreaddelegate-----%@",[NSThread currentThread]);
});
NSLog(@"+++++++++");
}
- (void)newThreaddelegate2
{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://api.apiopen.top/recommendPoetry"]];
//设置代理
//代理方法默认在主线程调用
//设置为立刻执行,跟delegate1没有区别
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
//设置代理方法在哪个线程中调用
[connection setDelegateQueue:[[NSOperationQueue alloc] init]];
//开始发送请求
//如果connection对象没有添加到runloop中,start会自动添加
//如果runloop没有开启,那么该方法内部会自动获得当前线程对应的runloop并开启,指定模式为默认
[connection start];
NSLog(@"%@",[NSThread currentThread]);
});
NSLog(@"+++++++++");
}
#pragma mark---------------------
#pragma mark NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"didReceiveResponse-------%@", [NSThread currentThread]);
}
@end
网友评论