在使用NSURLConnection 时异步请求的坑 以及NSRunLoop 强制停止

  • 在使用NSURLConnection 时异步请求的坑
    • 当我们使用子线程创建NSURLConnection异步请求时发现请求无响应 ?
    • 我们需要开启子线程的NSRunLoop
    • 如下
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];
        
        self.runLoop = CFRunLoopGetCurrent();
        
        // 启动runLoop
        CFRunLoopRun();
    });
  • 如何取消NSRunLoop
    • 当我们想强制取消NSRunLoop时 需创建CFRunLoopRef 对应 CFRunLoopStop(self.runLoop) 停止RunLoop
  • 代码
#import "ViewController.h"

@interface ViewController () 
/** runLoop */
@property (nonatomic, assign) CFRunLoopRef runLoop;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    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];
        
        self.runLoop = CFRunLoopGetCurrent();
        
        // 启动runLoop
        CFRunLoopRun();
    });
}

#pragma mark - 
- (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

你可能感兴趣的:(在使用NSURLConnection 时异步请求的坑 以及NSRunLoop 强制停止)