Question

I have an NSURLConnection that connects to a PHP API I have made. That PHP API responds with data. Since it is a dynamic application, I do this to tell the content length:

ob_start('scAPIHandler');    

function scAPIHandler($buffer){

    header('Content-Length: '.strlen($buffer));

    return $buffer;

}

At the beginning of the API file, which then later outputs whatever is necessary. However, when the

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 

function fires, the value of response.expectedContentLength is -1. When I try connecting not to my PHP API, but some images on the web, the correct expected content length is shown. Is there any way I can make my PHP API tell the NSURLResponse the content length to expect? The content-length header does not seem to work.

Thanks in advance!

Was it helpful?

Solution

Ok, I've figured it out. I used

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

    NSDictionary *responseHeaders = ((NSHTTPURLResponse *)response).allHeaderFields;

    NSLog(@"headers: %@", responseHeaders.description);

}

this method to figure out the headers that my iOS application was receiving, and I compared them with the headers that curl printed when connecting to the same URL. Turns out, there was a discrepancy between the headers that curl showed and that Objective-C did. Admittedly, it boggles my mind a lot, and I have no idea why that would happen, but I found a solution:

ob_start('scAPIHandler');    

function scAPIHandler($buffer){

    header('Custom-Content-Length: '.strlen($buffer));

    return $buffer;

}

The Custom-Content-Length did appear in Objective-C, and I simply took my custom header

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

    self.expectedContentLength = response.expectedContentLength;
    self.receivedData.length = 0;

    NSDictionary *responseHeaders = ((NSHTTPURLResponse *)response).allHeaderFields;

    if(self.expectedContentLength < 0){

        // take my own header

        NSString *actualContentLength = responseHeaders[@"Custom-Content-Length"];

        if(actualContentLength && actualContentLength.length > 0){

            self.expectedContentLength = actualContentLength.longLongValue;

        }

    }

}

and overwrote the expected content length.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top