Envoltório de bloqueio NSURLConnection implementado com semáforos [fechado]

Para o meu projeto mais recente, me deparei com a necessidade de:

baixar dados de forma bloqueante (para iniciar em um thread de segundo plano)mas também processa progressivamente os dados à medida que são recebidos (já que os dados baixados poderiam facilmente ser 100M, então não era eficiente armazenar tudo em um único NSData *)

Assim, eu precisava usar um objeto NSURLConnection assíncrono (para poder receber os dados progressivamente), mas envolvê-lo em um contêiner que bloquearia o encadeamento de chamada "entre" dois sucessivosconnection:didReceiveData: delegar chamadas e atéconnectionDidFinishLoading: ouconnection:didFailWithError: foram chamados.

Pensei em compartilhar minha solução, pois levei mais de algumas horas para reunir os códigos corretos encontrados aqui e ali (no StackOverflow e em outros fóruns).

O código basicamente lança um novoNSURLConnection em um segmento de fundo (dispatch_get_global_queue), define o ciclo de execução para poder receber as chamadas de representantes e usadispatch_semaphores para bloquear a chamada e os threads de segundo plano de uma maneira "alternada". odispatch_semaphores código é bem embrulhado dentro de um costumeProducerConsumerLock classe.

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

A classe BlockingConnection pode ser usada a partir do thread principal (mas isso bloquearia o thread principal) ou de uma fila personalizada:

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");
});

Se você tem algum comentário ou sugestão, por favor seja bem vindo!

questionAnswers(0)

yourAnswerToTheQuestion