IOS之UIWebView的使用
剛接觸IOS開發1年多,現在對於 混合式 移動端開發越來越流行,因為開發成本上、速度上都比傳統的APP開發要好,混合式開發 是傳統模式與PC網頁端相結合的模式。那麼提到了 APP的混合模式開發,在Android開發中有WebView作為混合模式開發的橋樑,當然在IOS中也同樣有一個 UIWebView 組件來作為混合模式開發的橋樑,那麼下面就對UIWebView的一些基本知識詳解一下。
一、UIWebView的基礎使用
1、建立UIWebView:
CGRect bouds = [[UIScreen manScreen]applicationFrame];
UIWebView* webView = [[UIWebView alloc]initWithFrame:bounds];
2、設定屬性:
webView.scalespageToFit = YES;//自動對頁面進行縮放以適應螢幕
webView.detectsPhoneNumbers = YES;//自動檢測網頁上的電話號碼,單擊可以撥打
3、顯示網頁視圖UIWebView:
[self.view addSubview:webView];
4、載入內容
NSURL* url = [NSURL URLWithString:@"http://www.baidu.com"];//建立URL
NSURLRequest* request = [NSURLRequest requestWithURL:url];//建立NSURLRequest
[webView loadRequest:request];//載入
也可以載入一個本地資源:
NSURL* url = [NSURL fileURLWithPath:filePath];//建立URL
NSURLRequest* request = [NSURLRequest requestWithURL:url];//建立NSURLRequest
[webView loadRequest:request];//載入
UIWebView 還支援將一個NSString對象作為源來載入。你可以為其提供一個基礎URL,來指導UIWebView對象如何跟隨連結和載入遠端資源:
[webView loadHTMLString:myHTML baseURL:[NSURL URLWithString:@"http://baidu.com"]];
5、導航
UIWebView類內部會管理瀏覽器的導航動作,通過goForward和goBack方法你可以控制前進與後退動作:
[webView goBack];
[webView goForward];
[webView reload];//重載
[webView stopLoading];//取消載入內容
6、UIWebViewDelegate委託代理
UIWebView支援一組委託方法,這些方法將在特定時間得到通知。要使用這些方法,必須先設定webView的委託:
webView.delegate = self;
下面每個委託方法的第一個參數都是指向一個UIwebview的指標,因此你可以將一個委託用於多個網頁視圖。
-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*) reuqest navigationType: (UIWebViewNavigationType)navigationType;//當網頁視圖被指示載入內容而得到通知。應當返回YES,這樣會進行載入。通過導航型別參數可以得到請求發起的原因,可以是以下任意值:
UIWebViewNavigationTypeLinkClicked
UIWebViewNavigationTypeFormSubmitted
UIWebViewNavigationTypeBackForward
UIWebViewNavigationTypeReload
UIWebViewNavigationTypeFormResubmitted
UIWebViewNavigationTypeOther
UIWebView控制項載入網頁的監聽函數方法:
-(void)webViewDidStartLoad:(UIWebView*)webView ;//當網頁視圖已經開始載入一個請求後,得到通知。
-(void)webViewDidFinishLoad:(UIWebView*)webView ;//當網頁視圖結束載入一個請求之後,得到通知。
-(void)webView:(UIWebView*)webView DidFailLoadWithError:(NSError*)error;//當在請求載入中發生錯誤時,得到通知。會提供一個NSSError對象,以標識所發生錯誤類型。
以上是IOS中UIWebView的基礎使用要點詳解,接下來一些UIWebView的常用注意點。
二、IOS中UIWebView常用注意點:
1、與UIWebView進行互動,調用web頁面中的需要傳參的函數時,參數需要帶單引號,或者雙引號(雙引號需要進行轉義在逸出字元前加\),在傳遞json字串時不需要加單引號或雙引號:
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *sendJsStr=[NSString stringWithFormat:@"openFile(\"%@\")",jsDocPathStr];
[webView stringByEvaluatingJavaScriptFromString:sendJsStr];
}
2、在該代理方法中判斷與webView的互動,可通過html裡定義的協議實現:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
3、只有在webView載入完畢之後在能夠調用對應頁面中的js方法。(對應方法如第1條).
4、為webView添加背景圖片:
approvalWebView.backgroundColor=[UIColor clearColor];
approvalWebView.opaque=NO;//這句話很重要,webView是否是不透明的,no為透明 在webView下添加個imageView展示圖片就可以了
5、擷取webView頁面內容資訊:
NSString *docStr=[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];//擷取web頁面內容資訊,此處擷取的是個json字串
SBJsonParser *parserJson=[[[SBJsonParser alloc]init]autorelease];
NSDictionary *contentDic=[parserJson objectWithString:docStr];//將json字串轉化為字典
6、 載入本地檔案的方法:
//第一種方法:
NSString* path = [[NSBundle mainBundle] pathForResource:name ofType:@"html" inDirectory:@"mobile"];//mobile是根目錄,name是檔案名稱,html是檔案類型
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]]; //載入本地檔案
//第二種方法:
NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
NSString *filePath = [resourcePath stringByAppendingPathComponent:@"mobile.html"];
NSString *htmlstring=[[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[uiwebview loadHTMLString:htmlstring baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
7、將檔案下載到本地址然後再用webView開啟:
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];
self.filePath = [resourceDocPath stringByAppendingPathComponent:[NSString stringWithFormat:@"maydoc%@",docType]];
NSData *attachmentData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:theUrl]];
[attachmentData writeToFile:filePath atomically:YES];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[attachmentWebView loadRequest:requestObj];
//刪除指定目錄下的檔案
NSFileManager *magngerDoc=[NSFileManager defaultManager];
[magngerDoc removeItemAtPath:filePath error:nil];
8、處理webView展示txt文檔亂碼問題:
if ([theType isEqualToString:@".txt"])
{
//txt分帶編碼和不帶編碼兩種,帶編碼的如UTF-8格式txt,不帶編碼的如ANSI格式txt
//不帶的,可以依次嘗試GBK和GB18030編碼
NSString* aStr = [[NSString alloc] initWithData:attachmentData encoding:NSUTF8StringEncoding];
if (!aStr)
{
//用GBK進行編碼
aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000632];
}
if (!aStr)
{
//用GBK編碼不行,再用GB18030編碼
aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000631];
}
//通過html語言進行排版
NSString* responseStr = [NSString stringWithFormat:
@""
""
"Text View"
""
""
"
"
"%@"
"/pre>"
""
"",
aStr];
[attachmentWebView loadHTMLString:responseStr baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
return;
} 9、使用webView載入本地或網路檔案整個流程:
1、 Loading a local PDF file into the web view
- (void)viewDidLoad {
[super viewDidLoad];
//從本地載入
NSString *thePath = [[NSBundle mainBundle] pathForResource:@"iPhone_User_Guide" ofType:@"pdf"];
if (thePath) {
NSData *pdfData = [NSData dataWithContentsOfFile:thePath];
[(UIWebView *)self.view loadData:pdfData MIMEType:@"application/pdf"
textEncodingName:@"utf-8" baseURL:nil];
}
//從網路載入
[self.myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]]];
}
2、The web-view delegate managing network loading
- (void)webViewDidStartLoad:(UIWebView *)webView
{
// starting the load, show the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
// finished loading, hide the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
// load error, hide the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// report the error inside the webview
NSString* errorString = [NSString stringWithFormat:
@"
An error occurred:
%@",
error.localizedDescription];
[self.myWebView loadHTMLString:errorString baseURL:nil];
}
3、Stopping a load request when the web view is to disappear
- (void)viewWillDisappear:(BOOL)animated
{
if ( [self.myWebView loading] ) {
[self.myWebView stopLoading];
}
self.myWebView.delegate = nil; // disconnect the delegate as the webview is hidden
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
/************/
引用自蘋果官方文檔(displaying web content) 10、尋找webView中的scrollview:
- (void) addScrollViewListener
{
UIScrollView* currentScrollView;
for (UIView* subView in self.webView.subviews) {
if ([subView isKindOfClass:[UIScrollView class]]) {
currentScrollView = (UIScrollView*)subView;
currentScrollView.delegate = self;
}
}
}
11、去掉webView的陰影,做成類似scrollView:
- (void)clearBackgroundWithColor:(UIColor*)color
{
// 去掉webview的陰影
self.backgroundColor = color;
for (UIView* subView in [self subviews])
{
if ([subView isKindOfClass:[UIScrollView class]]) {
for (UIView* shadowView in [subView subviews])
{
if ([shadowView isKindOfClass:[UIImageView class]]) {
[shadowView setHidden:YES];
}
}
}
}
}
12、取消長按webView上的連結彈出actionSheet的問題:
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout = 'none';"];
}
13、取消webView上的超級連結載入問題:
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if (navigationType==UIWebViewNavigationTypeLinkClicked) {
return NO;
}
else {
return YES;
}
}
14、webView在ios5.1之前的bug:在之前的工程中使用webView載入附件,webView支援doc,excel,ppt,pdf等格式,但這些附件必須先下載到本地然後在載入到webView上才可以顯示, 當附件下載到本地之後剛剛開始載入到webView上時,此時退出附件頁面會導致程式崩潰。會崩潰是由於webView控制項內部沒有把相關代理取消掉,所以導致退出之後程式崩潰。
webView在5.1上的bug:之前項目需求要webView可以左右活動,但在往webView上載入頁面時導致頁面載入不全,這個bug是由於webView本身的緩衝所致。(還有待研究)
15、在使用webView進行新浪微博分享時,webView會自動儲存登陸的cookie導致項目中的分享模組有些問題,刪除 webView的cookie的方法:
-(void)deleteCookieForDominPathStr:(NSString *)thePath
{
//刪除本地cookie,thePath為cookie路徑通過列印cookie可知道其路徑
for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
if([[cookie domain] isEqualToString:thePath]) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
}
}
16、在UIWebView中使用flashScrollIndicators
使用UIScrollView時,我們可以使用flashScrollIndicators方法顯示滾動標識然後消失,告知使用者此頁面可以滾動,後面還有更多內容。UIWebView內部依賴於UIScrollView,但是其沒有flashScrollIndicators方法,但可以通過其他途徑使用此方法,如下所示。
for (id subView in [webView subviews])
{ if ([subView respondsToSelector:@selector(flashScrollIndicators)])
{
[subView flashScrollIndicators];
}
}
上述程式碼片段可以到webViewDidFinishLoad回調中使用,載入完網頁內容後flash顯示滾動標識。
17、根據內容擷取UIWebView的高度:
有時候需要根據不同的內容調整UIWebView的高度,以使UIWebView剛好裝下所有內容,不用拖動,後面也不會留白。有兩種方式可根據載入內容擷取UIWebView的合適高度,但都需要在網頁內容載入完成後才可以,即需要在webViewDidFinishLoad回調中使用。
①.使用sizeThatFits方法。
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
CGRect frame = webView.frame;
frame.size.height = 1;
webView.frame = frame;
CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
frame.size = fittingSize;
webView.frame = frame;
}
sizeThatFits方法有個問題,如果當前UIView的大小比剛好合適的大小還大,則返回當前的大小,不會返回最合適的大小值,所以使用sizeThatFits前,先將UIWebView的高度設為最小,即1,然後再使用sizeThatFits就會返回剛好合適的大小。
②、使用JavaScript
- (void)webViewDidFinishLoad:(UIWebView *)webView
{ CGRect frame = webView.frame;
NSString *fitHeight = [webview stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"];
frame.size.height = [fitHeight floatValue];
webView.frame = frame;
}
總結:
首先 對IOS開發中的UIWebView控制項的基本使用進行初步的詳解,提到了建立、設定屬性、設定背景、怎麼樣
加載網頁內容等一系列的基礎點,然後闡述使用UIWebView控制項時常用用注意點,經常需要用到的地方,需要注意
的地方,使得對開發ios APP混合模式的橋樑---UIWebView控制項更加的瞭解、熟悉。UIWebView既能夠載入伺服器
提供的URI,又能夠載入本地的資源檔,還能夠載入伺服器返回的網頁介面代碼,可想而知UIWebView是多麼強
大的一控制項橋樑,以後在開發中使用到的地方會越來越多。