问题描述
我创建了一个 UIProgressView
。但我使用 NSTimer
到 UIProgressView的
进程。现在,我需要在加载URL时集成 UIProgressView
进程。 UIProgressView的
大小将取决于 NSURLConnection的
数据。
I created a UIProgressView
. But i used NSTimer
to UIProgressView's
process . Now I need to integrate UIProgressView
process, when URL is loading. UIProgressView's
size will be depends upon the NSURLConnection's
data.
我使用以下代码 NSURLConnection
。
-(void)load {
NSURL *myURL = [NSURL URLWithString:@"http://feeds.epicurious.com/newrecipes"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
responseData = [[NSMutableData alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
UIAlertView *alert = [[UIAlertView alloc] init];
[alert setTitle:@"Warning"];
[alert setMessage:@"Network Connection Failed?"];
[alert setDelegate:self];
[alert addButtonWithTitle:@"Yes"];
[alert show];
[alert release];
NSLog(@"Error");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
responsetext = [[[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding] autorelease];
}
推荐答案
在didReceiveResponse函数中你可以获取总文件大小如下:
_totalFileSize = response.expectedContentLength;
。
In your didReceiveResponse function you could get the total filesize like so:_totalFileSize = response.expectedContentLength;
.
在didReceiveData函数中然后你可以加总计收到的总字节数:
_receivedDataBytes + = [数据长度];
In your didReceiveData function you can then add up to a total bytes received counter:_receivedDataBytes += [data length];
现在,为了将进度条设置为正确的大小,您可以执行以下操作:
MyProgressBar.progress = _receivedDataBytes /(float)_totalFileSize
Now in order to set the progressbar to the correct size you can simply do:MyProgressBar.progress = _receivedDataBytes / (float)_totalFileSize
(在didReceiveData函数或代码中的其他位置)
(either in the didReceiveData function or somewhere else in your code)
不要忘记添加保存数字的变量字节到你的班级!
Don't forget to add the variables that hold the number of bytes to your class!
我希望这会有所帮助..
I hope this helps..
编辑:这是你如何实现代表以更新进度视图
Here's how you could implement the delegates in order to update progressview
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
_totalFileSize = response.expectedContentLength;
responseData = [[NSMutableData alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
_receivedDataBytes += [data length];
MyProgressBar.progress = _receivedDataBytes / (float)_totalFileSize;
[responseData appendData:data];
}
这篇关于在UIProgressView上添加NSURLConnection加载过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!