与信号量实现NSURLConnection的阻挡封套[关闭](NSURLConnection blo

2019-07-04 14:34发布

对于我最近的项目,我偶然发现需要:

  • 在阻塞的方式下载数据(在后台线程启动)
  • 而且逐步处理作为其被接收的数据(如下载的数据可以很容易地100M所以它是没有效率它的所有存储在一个大的NSData *)

因而我需要使用异步NSURLConnection的对象(为了能够逐渐地接收数据),但在容器中,将阻塞调用线程“在...之间”两个连续的包装它connection:didReceiveData:委托呼叫,以及直到connectionDidFinishLoading:connection:didFailWithError:被称为。

我想我会分享我的解决方案,我花了超过几个小时放在一起代码右边的片到处可见(StackOverflow上和其他论坛)。

该代码基本上推出一个新的NSURLConnection在后台线程( dispatch_get_global_queue ),将运行循环,以能够接收代表通话,并使用dispatch_semaphores可以阻塞调用和后台线程在“交替”的方式。 该dispatch_semaphores代码是很好的包裹自定义里面ProducerConsumerLock类。

BlockingConnection.m

#import "BlockingConnection.h"
#import "ProducerConsumerLock.h"

@interface BlockingConnection()

@property (nonatomic, strong) ProducerConsumerLock* lock;

@end

@implementation BlockingConnection

- (id)initWithURL:(NSURL*) url callback:(void(^)(NSData* data)) callback {
    if (self = [super init]) {
        self.lock = [ProducerConsumerLock new];

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
            [NSURLConnection connectionWithRequest:request delegate:self];
            while(!self.lock.finished) {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            }
        });

        [self.lock consume:^(NSData* data) {
            if (callback != nil) {
                callback(data);
            }
        }];
    }
    return self;
}

+ (void) connectionWithURL:(NSURL*) url callback:(void(^)(NSData* data)) callback {
    BlockingConnection* connection;
    connection = [[BlockingConnection alloc] initWithURL:url callback:callback];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.lock produce:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [self.lock produce:nil];
    [self.lock finish];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [self.lock finish];
}

@end

ProducerConsumerLock.h

@interface ProducerConsumerLock : NSObject

@property (atomic, readonly) BOOL finished;

- (void) consume:(void(^)(id object)) block;
- (void) produce:(id) object;
- (void) finish;

@end

ProducerConsumerLock.m

#import "ProducerConsumerLock.h"

@interface ProducerConsumerLock() {
    dispatch_semaphore_t consumerSemaphore;
    dispatch_semaphore_t producerSemaphore;
    NSObject* _object;
}

@end

@implementation ProducerConsumerLock

- (id)init {
    if (self = [super init]) {
        consumerSemaphore = dispatch_semaphore_create(0);
        producerSemaphore = dispatch_semaphore_create(0);
        _finished = NO;
    }
    return self;
}

- (void) consume:(void(^)(id)) block {
    BOOL finished = NO;
    while (!finished) {
        dispatch_semaphore_wait(consumerSemaphore, DISPATCH_TIME_FOREVER);
        finished = _finished;
        if (!finished) {
            block(_object);
            dispatch_semaphore_signal(producerSemaphore);
        }
    }
}

- (void) produce:(id) object {
    _object = object;
    _finished = NO;
    dispatch_semaphore_signal(consumerSemaphore);
    dispatch_semaphore_wait(producerSemaphore, DISPATCH_TIME_FOREVER);
}

- (void) finish {
    _finished = YES;
    dispatch_semaphore_signal(consumerSemaphore);
}

- (void)dealloc {
    dispatch_release(consumerSemaphore);
    dispatch_release(producerSemaphore);
}

@end

所述BlockingConnection类可以从主线程被使用(但是这会阻塞主线程)或从自定义队列:

dispatch_async(queue, ^{
    [BlockingConnection connectionWithURL:url callback:^(NSData *data) {
        if (data != nil) {
            //process the chunk of data as you wish
            NSLog(@"received %u bytes", data.length);
        } else {
            //an error occurred
        }
    }];
    NSLog(@"finished downloading");
});

如果您有任何意见或建议,请欢迎!

文章来源: NSURLConnection blocking wrapper implemented with semaphores [closed]