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