1

I a using STHTTPRequest to fetch JSON data in an IOS App. Please see the code below. When i am testing on Iphone 6 IOS8.0, Sometimes the code is going into error block. Its not happening always , only sometimes. Could anyone help ? Thank u

if(showActivity)
{
    [self ShowActivityIndicatorWithTitle:@"Loading..."];
}

STHTTPRequest *request1 = [STHTTPRequest requestWithURLString:[NSString stringWithFormat:@"%@%@",kBaseUrl,api]];
[request1 setTimeoutSeconds:120.0f];
[request1 setHeaderWithName:@"Content-Type" value:@"application/x-www-form-urlencoded"];
[request1 setHTTPMethod:@"POST"];

request1.rawPOSTData = [postData dataUsingEncoding:NSUTF8StringEncoding];

request1.completionDataBlock = ^(NSDictionary *headers, NSData* data)
{
    [self HideActivityIndicator];

    if(handler != nil)
    {
        NSError* connectionError;

        handler(JSONObjectFromData(data),connectionError);
    }

};

request1.errorBlock=^(NSError *error)
{
    NSLog(@"Error: %@", [error localizedDescription]);
    if(error != nil)
    {
        [[[UIAlertView alloc] initWithTitle:@"Connection Error !" message:kAlertInternetConnection delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil] show];
        [self HideActivityIndicator];

    }
};


[request1 startAsynchronous];
  • @nst Could you help ? – user2242861 Jun 24 '15 at 14:33
  • What is the error, then? – nst Jun 25 '15 at 08:52
  • Thank u @nst for the response, The error is "The Network connection was Lost". I am using Apache, PHP as webservice background that returns. Also using HTTPS. I hae checked the header using charles proxy. I think its connection alive error. I have added code [request1 setHeaderWithName:@"Connection" value:@"Keep-Alive"]; [request1 setHeaderWithName:@"Accept-Encoding" value:@"gzip,deflate"]; Still the Keep-alive showing as NO. Any ideas? – user2242861 Jun 25 '15 at 15:13
  • I would need a specific URL to test. Can you share the request in curl format? – nst Jun 27 '15 at 07:50

2 Answers2

0

I think i found the solution. Basically IOS takes the "Keep Alive" Parameter from first response, and thinks the connection is persistent. When the next JSON call is made, IOS is trying to use existing connection, which is expired. I have added header('Connection: close'); in each PHP web service. I am telling ios in each web service that the connection is closed. I am not sure if it is good way to do it. I have tested for 20 min on device. Its working. I appreciate any thoughts on this.

0

In PHP I added:

ob_end_clean();
header("Connection: close");
ignore_user_abort(true); // just to be safe
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Content-Length: ' . filesize($file));
readfile($file);

And it worked!

maxisme
  • 3,974
  • 9
  • 47
  • 97