6

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

  • 以阻塞方式下载数据(在后台线程中启动)
  • 但也会在接收数据时逐步处理数据(因为下载的数据很容易达到 100M,因此将其全部存储在一个大的 NSData* 中效率不高)

因此,我需要使用异步 NSURLConnection 对象(以便能够逐步接收数据),但将其包装在一个容器中,该容器将阻塞调用线程“介于”两个连续connection:didReceiveData:委托调用之间,直到其中一个connectionDidFinishLoading:或被connection:didFailWithError:调用。

我想我会分享我的解决方案,因为我花了几个小时才把到处找到的正确代码组合在一起(在 StackOverflow 和其他论坛上)。

代码基本上在NSURLConnection后台线程(代码很好地包装在自定义类中。dispatch_get_global_queuedispatch_semaphoresdispatch_semaphoresProducerConsumerLock

阻塞连接.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

生产者消费者锁.h

@interface ProducerConsumerLock : NSObject

@property (atomic, readonly) BOOL finished;

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

@end

生产者消费者锁.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");
});

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

4

0 回答 0