NSURLConnection 接收数据的百分比

NSURLConnection Receiving Data in Percentage

我有一个简单的NSURLConnection 我想获取解析数据的进度百分比。那就是加载的百分比。是否可以计算。 这个我试过了,

-(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;
}

此处,expectedBytes 得到 -1。 json link 正在得到 json 结果。 让我知道如何计算加载进度。

使用下面的代码。这对你有用,简单易行。

-(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;
}