2014-02-28 49 views
0

我想从url下载视频时显示进度条。我无法弄清楚我出错的地方,并且expectedContentLength总是显示-1。这是代码。带NSURLConnection的进度条

-(void)getResource{ 
bytesReceived = 0; 
self.progressView.progress = 0.0; 
NSString *string = @“MY_URL"; 
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL: 
[NSURL URLWithString:string]]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-length"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
self.feedConnection = [[NSURLConnection alloc]initWithRequest:request delegate:self] 
} 


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ 
self.responseData = [NSMutableData data]; 
[self.responseData setLength:0]; 
float length = [response expectedContentLength]; 
expectedBytes = [NSNumber numberWithUnsignedInteger:length]; 
NSLog(@"expected bytes %f %@",length,expectedBytes); 
} 

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ 
[self.responseData appendData:data]; 
float progress = (float)[self.responseData length]/[expectedBytes floatValue]; 
NSLog(@"%f/%f is %f", (float)[self.responseData length] ,[expectedBytes floatValue],progress); 
self.progressView.progress = progress; 
} 

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ 
    self.feedConnection = nil; 
} 

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{ 
self.feedConnection = nil; 
[self.view setBackgroundColor:[UIColor blackColor]]; 
[self fetchedData:self.responseData]; 
self.responseData = nil; 
} 

回答

2

我认为,你可以使用NSURLConnectionDownloadDelegate方法,其中将得到totalBytes以及有多少数据被下载。

- (void)connection:(NSURLConnection *)connection 
     didWriteData:(long long)bytesWritten 
    totalBytesWritten:(long long)totalBytesWritten 
expectedTotalBytes:(long long) expectedTotalBytes;