NSURLConnection以百分比形式接收数据

时间:2015-02-20 04:18:44

标签: ios objective-c nsurlconnection

我有一个简单的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链接正在获取jsonResult。 让我知道如何计算加载进度。

1 个答案:

答案 0 :(得分:1)

使用以下代码。这对您有用,简单易行。

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