如何在加载UIWebView时使用UIProgressView?

我正在开发一个应用程序,我在UIWebView中加载一个urlrequest,它发生成功。

但现在我正试图显示一个UIProgressView加载进行时(从0.0到1.0),这是随着加载进度dynamic改变。

我怎样才能做到这一点?

UIWebView不会在正常模式下给你任何进度信息。 你需要做的是首先使用NSURLConnectionasynchronous获取你的数据。 当NSURLConnection委托方法connection:didReceiveResponse ,您将从expectedContentLength获取数字并将其用作最大值。 然后,在委托方法connection:didReceiveData ,您将使用NSData实例的length属性来告诉您有多远,所以您的进度分数将是length / maxLength ,规范化为0.0到1.0之间。

最后,你要用数据而不是URL来初始化webview(在你的connection:didFinishLoading委托方法)。

两个警告:

  1. NSURLResponse的expectedContentLength属性有可能是-1NSURLReponseUnknownLength常量)。 在这种情况下,我会build议抛出一个标准的UIActivityIndi​​cator,你closuresconnection:didFinishLoading

  2. 确保每当你从一个NSURLConnection委托方法中操作一个可见的控件时,你可以通过调用performSelectorOnMainThread:否则你将开始得到可怕的EXC_BAD_ACCESS错误。

使用这种技术,当你知道你应该得到多less数据时,你可以显示进度条,当你不知道的时候,你可以显示一个微调。

您可以尝试使用UIWebView的这个使用私有UIWebView方法的子类 – 因此,这个解决scheme不是100%的AppStore安全(尽pipe一些应用几乎100%使用它:Facebook,Google应用,…)。

https://github.com/petr-inmite/imtwebview

使用NSURLConnection两次获取相同的数据,浪费时间,因为它可以减慢用户交互它加载数据两次,消耗互联网data.It最好是做一个基于定时器uiprogress和当webview成功地加载网页将显示uiprogress加载。在这种情况下,您可以显示一个dynamicuiprogress每次网页加载..不要忘了创build一个uiprogress视图,并将其命名为myProgressview并将其设置在文件所有者的。

这是代码希望它帮助

 @synthesize myProgressView; - (void)updateProgress:(NSTimer *)sender { //if the progress view is = 100% the progress stop if(myProgressView.progress==1.0) { [timer invalidate]; } else //if the progress view is< 100% the progress increases myProgressView.progress+=0.5; } - (void)viewDidLoad { //this is the code used in order to load the site [super viewDidLoad]; NSString *urlAddress = @"http://www.playbuzz.org/"; myWebview.delegate = self; [myWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlAddress]]]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)webViewDidFinishLoad:(UIWebView *)webView { ///timer for the progress view timer=[[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateProgress:) userInfo:myProgressView repeats:YES]retain]; } - (void)dealloc { [myProgressView release]; [super dealloc]; } @end 

这个代码和想法真的帮助我解决我的问题。