1、與webView進行交互,調用web頁面中的須要傳參的函數時,參數須要帶單引號,或者雙引號(雙引號須要進行轉義在轉義字符前加\),在傳遞json字符串時不須要加單引號或雙引號。 html
-(void)webViewDidFinishLoad:(UIWebView *)webView { NSString *sendJsStr=[NSString stringWithFormat:@"openFile(\"%@\")",jsDocPathStr]; [webView stringByEvaluatingJavaScriptFromString:sendJsStr]; }
二、在該代理方法中判斷與webView的交互,可經過html裏定義的協議實現 ios
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType三、只有在webView加載完畢以後在可以調用對應頁面中的js方法。(對應方法如第一條)
四、爲webView添加背景圖片 web
approvalWebView.backgroundColor=[UIColor clearColor]; approvalWebView.opaque=NO;//這句話很重要,webView是不是不透明的,no爲透明 //在webView下添加個imageView展現圖片就能夠了
五、獲取webView頁面內容信息 json
NSString *docStr=[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];//獲取web頁面內容信息,此處獲取的是個json字符串 SBJsonParser *parserJson=[[[SBJsonParser alloc]init]autorelease]; NSDictionary *contentDic=[parserJson objectWithString:docStr];//將json字符串轉化爲字典
六、加載本地文件的方法 緩存
第一種方法: 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]]];
七、將文件下載到本地址而後再用webView打開 cookie
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];八、處理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: @"<HTML>" "<head>" "<title>Text View</title>" "</head>" "<BODY>" "<pre>" "%@" "/pre>" "</BODY>" "</HTML>", aStr]; [attachmentWebView loadHTMLString:responseStr baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]]; return; }
9 、使用webView加載本地或網絡文件整個流程 網絡
一、 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/"]]]; } 二、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: @"<html><center><font size=+5 color='red'>An error occurred:<br>%@</font></center></html>", error.localizedDescription]; [self.myWebView loadHTMLString:errorString baseURL:nil]; } 三、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)
十、查找webView中的scrollview app
- (void) addScrollViewListener { UIScrollView* currentScrollView; for (UIView* subView in self.webView.subviews) { if ([subView isKindOfClass:[UIScrollView class]]) { currentScrollView = (UIScrollView*)subView; currentScrollView.delegate = self; } } }
十一、去掉webView的陰影,作成相似scrollView dom
- (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]; } } } } }
十二、取消長按webView上的連接彈出actionSheet的問題 ide
-(void)webViewDidFinishLoad:(UIWebView *)webView { [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout = 'none';"]; }1三、取消webView上的超級連接加載問題
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if (navigationType==UIWebViewNavigationTypeLinkClicked) { return NO; } else { return YES; } }
1四、1、webView在ios5.1以前的bug:在以前的工程中使用webView加載附件,webView支持doc,excel,ppt,pdf等格式,但這些附件必須先下載到本地而後在加載到webView上才能夠顯示, 當附件下載到本地以後剛剛開始加載到webView上時,此時退出附件頁面會致使程序崩潰。會崩潰是因爲webView控件內部沒有把相關代理取消掉,因此致使退出以後程序崩潰。
2、webView在5.1上的bug:以前項目需求要webView能夠左右活動,但在往webView上加載頁面時致使頁面加載不全,這個bug是因爲webView自己的緩存所致。(還有待研究)
1五、在使用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]; } } }
1六、在UIWebView中使用flashScrollIndicators
使用UIScrollView時,咱們可使用flashScrollIndicators方法顯示滾動標識而後消失,告知用戶此頁面能夠滾動,後面還有更多內容。UIWebView內部依賴於UIScrollView,可是其沒有flashScrollIndicators方法,但能夠經過其餘途徑使用此方法,以下所示。
for (id subView in [webView subviews]) { if ([subView respondsToSelector:@selector(flashScrollIndicators)]) { [subView flashScrollIndicators]; } }上述代碼片斷能夠到webViewDidFinishLoad回調中使用,加載完網頁內容後flash顯示滾動標識。
1七、根據內容獲取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; }
參考:
Three useful UIWebView tweaks
How to determine UIWebView height based on content, within a variable height UITableView?
How to determine the content size of a UIWebView?
clientHeight,offsetHeight和scrollHeight區別