gpt4 book ai didi

ios - 在 UIProgressView 上添加 NSURLConnection 加载过程

转载 作者:可可西里 更新时间:2023-11-01 04:12:03 24 4
gpt4 key购买 nike

我创建了一个 UIProgressView。但是我使用 NSTimerUIProgressView 的 进程。现在我需要在加载 URL 时集成 UIProgressView 进程。 UIProgressView 的 大小将取决于 NSURLConnection 的 数据。

我将以下代码用于 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;

然后,在您的 didReceiveData 函数中,您可以添加总字节数接收计数器:_receivedDataBytes += [数据长度];

现在为了将进度条设置为正确的大小,您可以简单地执行以下操作:MyProgressBar.progress = _receivedDataBytes/(float)_totalFileSize

(在 didReceiveData 函数中或代码中的其他地方)

不要忘记将保存字节数的变量添加到您的类中!

希望对你有帮助

编辑:以下是您如何实现委托(delegate)以更新进度 View

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

关于ios - 在 UIProgressView 上添加 NSURLConnection 加载过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4255261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com