Search code examples
iosafnetworking-2

Infinite loop in connection:didReceiveData in AFURLConnectionOperation.m


I am using AFNetworking2 for my iOS project which requires extensive image loading.

After downloading a certain number of images, all outgoing requests are queued in the operation queue and never go out.

I found out that is because in

AFURLConnectionOperation.m,(void)connection:didReceiveData

there is a while(YES) loop and it only breaks when

[self.outputStream hasSpaceAvailable]

or when

self.outputStream.streamError

occurs.

But, in my case, the [self.outputStream hasSpaceAvailable] returns NO, and the operation remains stuck in the while (YES) loop.

Has anyone experienced the issue, and what is the solution?

Here is the code of

AFURLConnectionOperation.m,(void)connection:didReceiveData

for context:

- (void)connection:(NSURLConnection __unused *)connection
    didReceiveData:(NSData *)data
{
    NSUInteger length = [data length];
    while (YES) { 
        ...
        if ([self.outputStream hasSpaceAvailable]) {
            ...
            break;
        }
        if (self.outputStream.streamError) {
            ....
            return;
        }
    }
    ...
}

Note: I am currently overriding that function with the code below to overcome the issue.

- (void)connection:(NSURLConnection __unused *)connection
    didReceiveData:(NSData *)data
{
    NSUInteger length = [data length];
    if ([self.outputStream hasSpaceAvailable]) {
        const uint8_t *dataBuffer = (uint8_t *) [data bytes];
        [self.outputStream write:&dataBuffer[0] maxLength:length];
    }
}

Solution

  • It seems like a bug in AFNetworking. see here.

    There is a committed fix mentioned in this issue, but it doesn't seem to be available in the latest version for some reason (2.5.4).