由于混合移動(dòng)終端的開發(fā)成本和速度均優(yōu)于傳統(tǒng)的應(yīng)用程序開發(fā),混合移動(dòng)終端的開發(fā)也越來越受大家的歡迎,混合開發(fā)是傳統(tǒng)模式與PC網(wǎng)絡(luò)終端的結(jié)合,下面就讓武林技術(shù)頻道小編帶你一起進(jìn)入下文了解IOS之UIWebView的基礎(chǔ)使用方法吧!
一、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)建URLNSURLRequest* request = [NSURLRequest requestWithURL:url];//創(chuàng)建NSURLRequest[webView loadRequest:request];//加載
也可以加載一個(gè)本地資源:
NSURL* url = [NSURL fileURLWithPath:filePath];//創(chuàng)建URLNSURLRequest* 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ā)起的原因,可以是以下任意值:UIWebViewNavigationTypeLinkClickedUIWebViewNavigationTypeFormSubmittedUIWebViewNavigationTypeBackForwardUIWebViewNavigationTypeReloadUIWebViewNavigationTypeFormResubmittedUIWebViewNavigationTypeOther
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)識所發(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 webviewNSString* 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)識然后消失,告知用戶此頁面可以滾動(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)識。
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ì)越來越多。
以上就是IOS之UIWebView的基礎(chǔ)使用方法,更多內(nèi)容請繼續(xù)關(guān)注武林技術(shù)頻道其它相關(guān)文章!
新聞熱點(diǎn)
疑難解答
圖片精選