2009-12-14 38 views
11

我正在开发一个应用程序,我在UIWebView中加载urlrequest,并且它成功发生。如何在加载UIWebView时使用UIProgressView?

但现在我试图显示一个UIProgressView加载过程中(从0.0开始到1.0),这是随着加载进度动态改变。

我该怎么做?

回答

21

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

最后,您将使用数据而不是URL初始化webview(在您的connection:didFinishLoading委托方法中)。

两个注意事项:

  1. 这是可能的NSURLResponse的expectedContentLength属性将是-1NSURLReponseUnknownLength不变)。在这种情况下,我会建议你在connection:didFinishLoading内部关闭一个标准的UIActivityIndi​​cator。

  2. 确保任何时候你的NSURLConnection的委托方法之一操作可见控制,您可以通过调用performSelectorOnMainThread:这样做 - 否则你会开始变得可怕EXC_BAD_ACCESS错误。

使用这种技术,可以显示一个进度条,当你知道你应该有多少数据获得,当你不知道的好手。

+0

在UIWebView加载请求顶部实现NSURLConnection数据提取的问题是,您要抓取相同的数据两次,这对轻量级连接是浪费的。您可以使用'loadData:MIMEType:textEncodingName:baseURL:'将NSData实例直接加载到UIWebView中,但这会损害使用UIWebView的其他方面。 – 2012-04-24 13:52:57

2

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

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

-2

使用NSURLConnection的你两次取相同的数据,浪费时间,因为它可以减缓它加载数据的两倍用户交互,占用网络data.It是更好地做一个uiprogress基于计时器和webview成功加载网页时,它会显示加载。在这种情况下,你可以显示一个动态uiprogress每次加载网页..不要忘了创建一个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 

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

相关问题