Search code examples
iosobjective-cnsurlconnection

NSURLConnection Receiving Data in Percentage


I have a simple NSURLConnection I want to get the parsing data progress percentage. That is how much percentage loaded. Is it possible to calculate. I have tried this,

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    urlData = [NSMutableData data];
    [urlData setLength:0];
  expectedBytes = [response expectedContentLength];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
float progressive = (float)[urlData length] / (float)expectedBytes;
}

here, expectedBytes getting -1. The json link is working getting jsonResult. Let me know how to Calculate the loading progress.


Solution

  • Use below code. This will work for you,Simple and easy.

    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response{
          urlData = [NSMutableData data];
          [urlData setLength:0];
          double expectedBytes = [[[response allHeaderFields] objectForKey:@"Content-Length"] doubleValue];
        }
    
    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
          float progressive = (float)[urlData length] / (float)expectedBytes;
    }