IOS之UIWebView的使用(基本知識(shí))
剛接觸IOS開發(fā)1年多,現(xiàn)在對于混合式移動(dòng)端開發(fā)越來越流行,因?yàn)殚_發(fā)成本上、速度上都比傳統(tǒng)的APP開發(fā)要好,混合式開發(fā)是傳統(tǒng)模式與PC網(wǎng)頁端相結(jié)合的模式。那么提到了 APP的混合模式開發(fā),在Android開發(fā)中有WebView作為混合模式開發(fā)的橋梁,當(dāng)然在IOS中也同樣有一個(gè) UIWebView 組件來作為混合模式開發(fā)的橋梁,那么下面就對UIWebView的一些基本知識(shí)詳解一下。
一、UIWebView的基礎(chǔ)使用
1、創(chuàng)建UIWebView:
CGRect bouds = [[UIScreen manScreen]applicationFrame];
UIWebView* webView = [[UIWebView alloc]initWithFrame:bounds];
2、設(shè)置屬性:
webView.scalespageToFit = YES;//自動(dòng)對頁面進(jìn)行縮放以適應(yīng)屏幕
webView.detectsPhoneNumbers = YES;//自動(dòng)檢測網(wǎng)頁上的電話號碼,單擊可以撥打
3、顯示網(wǎng)頁視圖UIWebView:
[self.view addSubview:webView];
4、加載內(nèi)容
NSURL* url = [NSURL URLWithString:@"http://www.baidu.com"];//創(chuàng)建URL NSURLRequest* request = [NSURLRequest requestWithURL:url];//創(chuàng)建NSURLRequest [webView loadRequest:request];//加載
也可以加載一個(gè)本地資源:
NSURL* url = [NSURL fileURLWithPath:filePath];//創(chuàng)建URL NSURLRequest* request = [NSURLRequest requestWithURL:url];//創(chuàng)建NSURLRequest [webView loadRequest:request];//加載
UIWebView 還支持將一個(gè)NSString對象作為源來加載。你可以為其提供一個(gè)基礎(chǔ)URL,來指導(dǎo)UIWebView對象如何跟隨鏈接和加載遠(yuǎn)程資源:
[webView loadHTMLString:myHTML baseURL:[NSURL URLWithString:@"http://baidu.com"]];
5、導(dǎo)航
UIWebView類內(nèi)部會(huì)管理瀏覽器的導(dǎo)航動(dòng)作,通過goForward和goBack方法你可以控制前進(jìn)與后退動(dòng)作:
[webView goBack]; [webView goForward]; [webView reload];//重載 [webView stopLoading];//取消載入內(nèi)容
6、UIWebViewDelegate委托代理
UIWebView支持一組委托方法,這些方法將在特定時(shí)間得到通知。要使用這些方法,必須先設(shè)定webView的委托:
webView.delegate = self;
下面每個(gè)委托方法的第一個(gè)參數(shù)都是指向一個(gè)UIwebview的指針,因此你可以將一個(gè)委托用于多個(gè)網(wǎng)頁視圖。
-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*) reuqest navigationType: (UIWebViewNavigationType)navigationType;//當(dāng)網(wǎng)頁視圖被指示載入內(nèi)容而得到通知。應(yīng)當(dāng)返回YES,這樣會(huì)進(jìn)行加載。通過導(dǎo)航類型參數(shù)可以得到請求發(fā)起的原因,可以是以下任意值: UIWebViewNavigationTypeLinkClicked UIWebViewNavigationTypeFormSubmitted UIWebViewNavigationTypeBackForward UIWebViewNavigationTypeReload UIWebViewNavigationTypeFormResubmitted UIWebViewNavigationTypeOther
UIWebView控件加載網(wǎng)頁的監(jiān)聽函數(shù)方法:
-(void)webViewDidStartLoad:(UIWebView*)webView ;//當(dāng)網(wǎng)頁視圖已經(jīng)開始加載一個(gè)請求后,得到通知。
-(void)webViewDidFinishLoad:(UIWebView*)webView ;//當(dāng)網(wǎng)頁視圖結(jié)束加載一個(gè)請求之后,得到通知。
-(void)webView:(UIWebView*)webView DidFailLoadWithError:(NSError*)error;//當(dāng)在請求加載中發(fā)生錯(cuò)誤時(shí),得到通知。會(huì)提供一個(gè)NSSError對象,以標(biāo)識(shí)所發(fā)生錯(cuò)誤類型。
以上是IOS中UIWebView的基礎(chǔ)使用要點(diǎn)詳解,接下來一些UIWebView的常用注意點(diǎn)。
二、IOS中UIWebView常用注意點(diǎn):
1、與UIWebView進(jìn)行交互,調(diào)用web頁面中的需要傳參的函數(shù)時(shí),參數(shù)需要帶單引號,或者雙引號(雙引號需要進(jìn)行轉(zhuǎn)義在轉(zhuǎn)義字符前加\),在傳遞json字符串時(shí)不需要加單引號或雙引號:
-(void)webViewDidFinishLoad:(UIWebView *)webView { NSString *sendJsStr=[NSString stringWithFormat:@"openFile(\"%@\")",jsDocPathStr]; [webView stringByEvaluatingJavaScriptFromString:sendJsStr]; }
2、在該代理方法中判斷與webView的交互,可通過html里定義的協(xié)議實(shí)現(xiàn):
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
3、只有在webView加載完畢之后在能夠調(diào)用對應(yīng)頁面中的js方法。(對應(yīng)方法如第1條).
4、為webView添加背景圖片:
approvalWebView.backgroundColor=[UIColor clearColor];
approvalWebView.opaque=NO;//這句話很重要,webView是否是不透明的,no為透明 在webView下添加個(gè)imageView展示圖片就可以了
5、獲取webView頁面內(nèi)容信息:
NSString *docStr=[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];//獲取web頁面內(nèi)容信息,此處獲取的是個(gè)json字符串
SBJsonParser *parserJson=[[[SBJsonParser alloc]init]autorelease];
NSDictionary *contentDic=[parserJson objectWithString:docStr];//將json字符串轉(zhuǎn)化為字典
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進(jìn)行編碼 aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000632]; } if (!aStr) { //用GBK編碼不行,再用GB18030編碼 aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000631]; } //通過html語言進(jìn)行排版 NSString* responseStr = [NSString stringWithFormat: @"" "" "" "" "%@" "/pre>" "" "", aStr]; [attachmentWebView loadHTMLString:responseStr baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]]; return; }
9、使用webView加載本地或網(wǎng)絡(luò)文件整個(gè)流程:
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]; } //從網(wǎng)絡(luò)加載 [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上才可以顯示, 當(dāng)附件下載到本地之后剛剛開始加載到webView上時(shí),此時(shí)退出附件頁面會(huì)導(dǎo)致程序崩潰。會(huì)崩潰是由于webView控件內(nèi)部沒有把相關(guān)代理取消掉,所以導(dǎo)致退出之后程序崩潰。
webView在5.1上的bug:之前項(xiàng)目需求要webView可以左右活動(dòng),但在往webView上加載頁面時(shí)導(dǎo)致頁面加載不全,這個(gè)bug是由于webView本身的緩存所致。(還有待研究)
15、在使用webView進(jìn)行新浪微博分享時(shí),webView會(huì)自動(dòng)保存登陸的cookie導(dǎo)致項(xiàng)目中的分享模塊有些問題,刪除 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時(shí),我們可以使用flashScrollIndicators方法顯示滾動(dòng)標(biāo)識(shí)然后消失,告知用戶此頁面可以滾動(dòng),后面還有 更多內(nèi)容。UIWebView內(nèi)部依賴于UIScrollView,但是其沒有flashScrollIndicators方法,但可以通過其他途徑使用 此方法,如下所示。
for (id subView in [webView subviews]) { if ([subView respondsToSelector:@selector(flashScrollIndicators)]) { [subView flashScrollIndicators]; } }
上述代碼片段可以到webViewDidFinishLoad回調(diào)中使用,加載完網(wǎng)頁內(nèi)容后flash顯示滾動(dòng)標(biāo)識(shí)。
17、根據(jù)內(nèi)容獲取UIWebView的高度:
有時(shí)候需要根據(jù)不同的內(nèi)容調(diào)整UIWebView的高度,以使UIWebView剛好裝下所有內(nèi)容,不用拖動(dòng),后面也不會(huì)留白。有兩種方式可根據(jù)加載內(nèi)容 獲取UIWebView的合適高度,但都需要在網(wǎng)頁內(nèi)容加載完成后才可以,即需要在webViewDidFinishLoad回調(diào)中使用。
①.使用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方法有個(gè)問題,如果當(dāng)前UIView的大小比剛好合適的大小還大,則返回當(dāng)前的大小,不會(huì)返回最合適的大小值,所以使用 sizeThatFits前,先將UIWebView的高度設(shè)為最小,即1,然后再使用sizeThatFits就會(huì)返回剛好合適的大小。
②、使用JavaScript
- (void)webViewDidFinishLoad:(UIWebView *)webView { CGRect frame = webView.frame; NSString *fitHeight = [webview stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"]; frame.size.height = [fitHeight floatValue]; webView.frame = frame; }
總結(jié):
首先 對IOS開發(fā)中的UIWebView控件的基本使用進(jìn)行初步的詳解,提到了創(chuàng)建、設(shè)置屬性、設(shè)置背景、怎么樣加載網(wǎng)頁內(nèi)容等一系列的基礎(chǔ)點(diǎn),然后闡述使用UIWebView控件時(shí)常用用注意點(diǎn),經(jīng)常需要用到的地方,需要注意的地方,使得對開發(fā)ios APP混合模式的橋梁---UIWebView控件更加的了解、熟悉。UIWebView既能夠加載服務(wù)器提供的URI,又能夠加載本地的資源文件,還能夠加載服務(wù)器返回的網(wǎng)頁界面代碼,可想而知UIWebView是多么強(qiáng)大的一控件橋梁,以后在開發(fā)中使用到的地方會(huì)越來越多。
相關(guān)文章
深入詳解Objective-C中的@Synchronized關(guān)鍵字
這篇文章主要為大家介紹了深入詳解Objective-C中的@Synchronized關(guān)鍵字,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03ios 使用xcode11 新建項(xiàng)目工程的步驟詳解
這篇文章主要介紹了ios 使用xcode11 新建項(xiàng)目工程 (值得注意的問題),本文分步驟通過圖文的形式給大家展示,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04上傳IPA出現(xiàn)的錯(cuò)誤提示“application loader“上傳出錯(cuò)解決方法
這篇文章主要介紹了上傳IPA出現(xiàn)的錯(cuò)誤提示“application loader“上傳出錯(cuò)解決方法的相關(guān)資料,需要的朋友可以參考下2017-06-06iOS Crash常規(guī)跟蹤方法及Bugly集成運(yùn)用詳細(xì)介紹
這篇文章主要介紹了iOS Crash常規(guī)跟蹤方法及Bugly集成運(yùn)用詳細(xì)介紹的相關(guān)資料,需要的朋友可以參考下2016-10-10iOS實(shí)現(xiàn)設(shè)備判斷是否安裝相關(guān)地圖(百度、高德等)
這篇文章主要給大家介紹了關(guān)于iOS如何實(shí)現(xiàn)設(shè)備判斷是否安裝相關(guān)地圖,比如百度、高德等,其實(shí)實(shí)現(xiàn)的方法還是很簡單,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友下面來一起看看吧。2018-01-01