[英]How to use UIProgressView while loading of a UIWebView?
我正在開發一個應用程序,我在UIWebView中加載urlrequest,它發生成功。
但是現在我正在嘗試在加載過程中顯示UIProgressView(從0.0開始到1.0),隨着加載的進度動態地改變。
我怎樣才能做到這一點?
UIWebView在正常模式下不會提供任何進度信息。 您需要做的是首先使用NSURLConnection異步獲取數據。 當NSURLConnection委托方法connection:didReceiveResponse
,您將獲取您從expectedContentLength
獲得的數字並將其用作最大值。 然后,在委托方法connection:didReceiveData
,您將使用NSData實例的length
屬性來告訴您離您有多遠,因此您的進度分數將為length / maxLength
,標准化為0.0到1.0之間。
最后,您將使用數據而不是URL(在您的connection:didFinishLoading
委托方法)初始化webview。
兩個警告:
NSURLResponse的expectedContentLength
屬性可能為-1 ( NSURLReponseUnknownLength
常量)。 在這種情況下,我建議拋出一個標准的UIActivityIndicator,你關閉內部connection:didFinishLoading
。
確保每次從NSURLConnection委托方法之一操作可見控件時,都可以通過調用performSelectorOnMainThread:
- 否則您將開始獲得可怕的EXC_BAD_ACCESS錯誤。
使用這種技術,當你知道你應該獲得多少數據時,你可以顯示一個進度條,當你不知道時,你可以顯示一個微調器。
您可以嘗試使用UIWebView的這個子類,它使用私有的UIWebView方法 - 因此,這個解決方案不是100%AppStore安全(盡管有些應用程序幾乎100%使用它:Facebook,Google應用程序......)。
使用NSURLConnection你會獲取相同的數據兩次,浪費時間,因為它可以減慢用戶交互速度,加載數據兩次,消耗互聯網數據。最好是基於計時器制作一個uiprogress,當webview成功加載網頁時將顯示uiprogress加載。在這種情況下,您可以在每次加載網頁時顯示動態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
這段代碼和想法真的幫助我解決了我的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.