本文转载至 http://www.verydemo.com/demo_c101_i46895.html

一、与webView进行交互,调用web页面中的需要传参的函数时,参数需要带单引号,或者双引号(双引号需要进行转义在转义字符前加\),在传递json字符串时不需要加单引号或双引号。

1 -(void)webViewDidFinishLoad:(UIWebView *)webView
2 {
3     NSString *sendJsStr=[NSString stringWithFormat:@"openFile(\"%@\")",jsDocPathStr];
4   [webView stringByEvaluatingJavaScriptFromString:sendJsStr];
5 }

2、在该代理方法中判断与webView的交互,可通过html里定义的协议实现

1 - (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType

3、只有在webView加载完毕之后在能够调用对应页面中的js方法。(对应方法如第一条)

4、为webView添加背景图片

1 approvalWebView.backgroundColor=[UIColor clearColor];
2 approvalWebView.opaque=NO;//这句话很重要,webView是否是不透明的,no为透明
3 //在webView下添加个imageView展示图片就可以了

5、获取webView页面内容信息

1 NSString *docStr=[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];//获取web页面内容信息,此处获取的是个json字符串
2  
3 SBJsonParser *parserJson=[[[SBJsonParser alloc]init]autorelease];
4  
5 NSDictionary *contentDic=[parserJson objectWithString:docStr];//将json字符串转化为字典

6、加载本地文件的方法

1 第一种方法:
2 NSString* path = [[NSBundle mainBundle] pathForResource:name ofType:@"html"inDirectory:@"mobile"];//mobile是根目录,name是文件名称,html是文件类型
3 [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]]; //加载本地文件
4 第二种方法:
5 NSString *resourcePath = [[NSBundle mainBundle] resourcePath]; 
6 NSString *filePath = [resourcePath stringByAppendingPathComponent:@"mobile.html"]; 
7 NSString *htmlstring=[[NSString alloc] initWithContentsOfFile:filePath  encoding:NSUTF8StringEncoding error:nil]; 
8 [uiwebview loadHTMLString:htmlstring baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];

7、将文件下载到本地址然后再用webView打开

01 NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];
02  self.filePath = [resourceDocPath stringByAppendingPathComponent:[NSString stringWithFormat:@"maydoc%@",docType]];
03 NSData *attachmentData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:theUrl]];
04 [attachmentData writeToFile:filePath atomically:YES];
05  NSURL *url = [NSURL fileURLWithPath:filePath];
06  NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
07  [attachmentWebView loadRequest:requestObj];
08 //删除指定目录下的文件
09  
10 NSFileManager *magngerDoc=[NSFileManager defaultManager];
11 [magngerDoc removeItemAtPath:filePath error:nil];

8、处理webView展示txt文档乱码问题

01 if ([theType isEqualToString:@".txt"])
02  {
03 //txt分带编码和不带编码两种,带编码的如UTF-8格式txt,不带编码的如ANSI格式txt
04 //不带的,可以依次尝试GBK和GB18030编码
05 NSString* aStr = [[NSString alloc] initWithData:attachmentData encoding:NSUTF8StringEncoding];
06 if (!aStr)
07 {
08 //用GBK<strong>进行</strong>编码
09 aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000632];
10 }
11 if (!aStr)
12 {
13 //用GBK编码不行,再用GB18030编码
14  aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000631];
15 }
16 //通过html语言<strong>进行</strong>排版
17  NSString* responseStr = [NSString stringWithFormat:
18                                  @"<HTML>"
19                                  "<head>"
20                                  "<title>Text View</title>"
21                                  "</head>"
22                                  "<BODY>"
23                                  "<pre>"
24                                  "%@"
25                                  "/pre>"
26                                  "</BODY>"
27                                  "</HTML>",
28                                  aStr];
29  [attachmentWebView loadHTMLString:responseStr baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
30         return;
31  }

9 、使用webView加载本地或网络文件整个流程

01 1、 Loading a local PDF file into the web view
02  
03 - (void)viewDidLoad {
04     [super viewDidLoad];
05  //从本地加载
06     NSString *thePath = [[NSBundle mainBundle] pathForResource:@"iPhone_User_Guide" ofType:@"pdf"];
07     if (thePath) {
08         NSData *pdfData = [NSData dataWithContentsOfFile:thePath];
09         [(UIWebView *)self.view loadData:pdfData MIMEType:@"application/pdf"
10             textEncodingName:@"utf-8" baseURL:nil];
11     }
12 //从网络加载
13 [self.myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]]];
14 }
15 2、The web-view delegate managing network loading
16  
17 - (void)webViewDidStartLoad:(UIWebView *)webView
18 {
19     // starting the load, show the activity indicator in the status bar
20     [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
21 }
22   
23 - (void)webViewDidFinishLoad:(UIWebView *)webView
24 {
25     // finished loading, hide the activity indicator in the status bar
26     [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
27 }
28   
29 - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
30 {
31     // load error, hide the activity indicator in the status bar
32     [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
33   
34     // report the error inside the webview
35     NSString* errorString = [NSString stringWithFormat:
36                              @"<html><center><font size=+5 color='red'>An error occurred:<br>%@</font></center></html>",
37                              error.localizedDescription];
38     [self.myWebView loadHTMLString:errorString baseURL:nil];
39 }
40 3、Stopping a load request when the web view is to disappear
41  
42 - (void)viewWillDisappear:(BOOL)animated
43 {
44     if ( [self.myWebView loading] ) {
45         [self.myWebView stopLoading];
46     }
47     self.myWebView.delegate = nil;    // disconnect the delegate as the webview is hidden
48     [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
49 }
50 /************/
51 引用自苹果官方文档(displaying web content)

10、查找webView中的scrollview

01 - (void) addScrollViewListener
02 {
03     UIScrollView* currentScrollView;
04     for (UIView* subView in self.webView.subviews) {
05         if ([subView isKindOfClass:[UIScrollView class]]) {
06             currentScrollView = (UIScrollView*)subView;
07             currentScrollView.delegate = self;
08         }
09     }
10 }

11、去掉webView的阴影,做成类似scrollView

01 - (void)clearBackgroundWithColor:(UIColor*)color
02 {
03   // 去掉webview的阴影
04   self.backgroundColor = color;
05   for (UIView* subView in [self subviews])
06   {
07     if ([subView isKindOfClass:[UIScrollView class]]) {
08       for (UIView* shadowView in [subView subviews])
09       {
10         if ([shadowView isKindOfClass:[UIImageView class]]) {
11           [shadowView setHidden:YES];
12         }
13       }
14     }
15   }
16  
17 }

12、取消长按webView上的链接弹出actionSheet的问题

1 -(void)webViewDidFinishLoad:(UIWebView *)webView
2 {
3  [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout = 'none';"];
4 }

13、取消webView上的超级链接加载问题

1 -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
2 {
3     if (navigationType==UIWebViewNavigationTypeLinkClicked) {
4         return NO;
5     }
6     else {
7         return YES;
8     }
9 }

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的方法

01 -(void)deleteCookieForDominPathStr:(NSString *)thePath
02 {
03     //删除本地cookie,thePath为cookie路径通过打印cookie可知道其路径   
04     for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
05          
06         if([[cookie domain] isEqualToString:thePath]) {
07              
08             [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
09         }
10     }
11 }

16、在UIWebView中使用flashScrollIndicators

使用UIScrollView时,我们可以使用flashScrollIndicators方法显示滚动标识然后消失,告知用户此页面可以滚动,后面还有更多内容。UIWebView内部依赖于UIScrollView,但是其没有flashScrollIndicators方法,但可以通过其他途径使用此方法,如下所示。

1 for (id subView in [webView subviews])
2 {   if ([subView respondsToSelector:@selector(flashScrollIndicators)])     
3      {
4        [subView flashScrollIndicators];
5      }
6 }

上述代码片段可以到webViewDidFinishLoad回调中使用,加载完网页内容后flash显示滚动标识。

17、根据内容获取UIWebView的高度

有时候需要根据不同的内容调整UIWebView的高度,以使UIWebView刚好装下所有内容,不用拖动,后面也不会留白。有两种方式可根据加载内容获取UIWebView的合适高度,但都需要在网页内容加载完成后才可以,即需要在webViewDidFinishLoad回调中使用。

①.使用sizeThatFits方法。

1 - (void)webViewDidFinishLoad:(UIWebView *)webView
2 {    
3     CGRect frame = webView.frame;   
4     frame.size.height = 1;    
5     webView.frame = frame;    
6     CGSize fittingSize = [webView sizeThatFits:CGSizeZero];    
7     frame.size = fittingSize;   
8     webView.frame = frame;
9 }

sizeThatFits方法有个问题,如果当前UIView的大小比刚好合适的大小还大,则返回当前的大小,不会返回最合适的大小值,所以使用sizeThatFits前,先将UIWebView的高度设为最小,即1,然后再使用sizeThatFits就会返回刚好合适的大小。

②、使用JavaScript

1 - (void)webViewDidFinishLoad:(UIWebView *)webView
2 {     CGRect frame = webView.frame;  
3       NSString *fitHeight = [webview stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"];    
4      frame.size.height = [fitHeight floatValue];   
5      webView.frame = frame;
6 }

参考:
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区别

与webView进行交互,webView小记的更多相关文章

  1. WebView JS交互 JSBridge 案例 原理 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  2. WebView JS交互 addJavascriptInterface MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  3. 客户端相关知识学习(十一)之Android H5交互Webview实现localStorage数据存储

    前言 最近有一个需求是和在app中前端本地存储相关的,所以恶补了一下相关知识 webView开启支持H5 LocalStorage存储 有些时候我们发现写的本地存储没有起作用,那是因为默认WebVie ...

  4. JS和webView的交互

    JSContext的交互方式最为简单快捷: 1.申明一个JSContext对象 self.jsRunner = [[JSContext alloc] init]; 2.在原生中定义申明一个JS函数方法 ...

  5. 【WebView】Android WebView中的Cookie操作

    Hybrid App(混合式应用)的开发过程中少不了与WebView的交互,在涉及到账户体系的产品中,包含了一种登录状态的传递.比如,在Native(原生)界面的登录操作,进入到Web界面时,涉及到账 ...

  6. Android WebView Memory Leak WebView内存泄漏

    在这次开发过程中,需要用到webview展示一些界面,但是加载的页面如果有很多图片就会发现内存占用暴涨,并且在退出该界面后,即使在包含该webview的Activity的destroy()方法中,使用 ...

  7. 安卓android WebView Memory Leak WebView内存泄漏

    Android WebView Memory Leak WebView内存泄漏 在这次开发过程中,需要用到webview展示一些界面,但是加载的页面如果有很多图片就会发现内存占用暴涨,并且在退出该界面 ...

  8. 背水一战 Windows 10 (65) - 控件(WebView): 对 WebView 中的内容截图, 通过 Share Contract 分享 WebView 中的被选中的内容

    [源码下载] 背水一战 Windows 10 (65) - 控件(WebView): 对 WebView 中的内容截图, 通过 Share Contract 分享 WebView 中的被选中的内容 作 ...

  9. android webview js交互 第一节 (java和js交互)

    转载请注明出处         挺帅的移动开发专栏  http://blog.csdn.net/wangtingshuai/article/details/8631835        在androi ...

随机推荐

  1. FragmentTransaction的commit的异步操作

    FragmentTransaction是异步的,commit()仅是相当于把操作加入到FragmentManager的队列,然后FragmentManager会在某一个时刻来执行,并不是立即执行.所以 ...

  2. django前后端数据传输学习记录

    在开发过程中会遇到这样的情况 后台返回了一堆的数据,是一个列表 例如 datas = [{"a":1, "b":2}, {"c": 3,&q ...

  3. EasyUI Tree 动态传递参数

    1.问题背景 一般出现在加载的时候,传递参数给后台,进行数据筛选,然后在加载tree渲染数据.所谓动态参数,可以是你的上一级节点node,或者是根节点node. 2.涉及方法 onBeforeLoad ...

  4. 转:Eclipse常见问题,快捷键收集

    Eclipse的编辑功能非常强大,掌握了Eclipse快捷键功能,能够大大提高开发效率.Eclipse中有如下一些和编辑相关的快捷键. 1.[ALT+/] Sysout+ System.out.pri ...

  5. 【HTML 元素】嵌入另一张HTML文档、通过插件嵌入内容、嵌入数字表现形式

    1.嵌入另一张HTML文档 iframe 元素允许在现有的HTML文档中嵌入另一张文档.下面代码展示了iframe元素的用法: <!DOCTYPE html> <html lang= ...

  6. js获取屏幕高度/浏览器高度

     1.window.screen.height window.screen.height:设备显示屏的高度 (1)分辨率为1080px的显示屏 (2)手机屏 2.window.screen.avail ...

  7. MySQL + Amoeba 负载均衡、主从备份方案

    1.  基本环境 4台内网虚拟机的操作系统都是ubuntu-14.04.4 64位 IP为:192.168.169.11.192.168.169.12.192.168.169.13.192.168.1 ...

  8. ubuntu安装firefox的flash插件

    1.下载插件 https://get.adobe.com/cn/flashplayer/ 下载tar.gz文件 2.解压缩 切换到下载目录,如果是默认下载的话,用 cd ~/下载/解压缩下载的文件 t ...

  9. swift 中的问号跟感叹号

    ?: 变量在使用过程中可能存在空值,则需要用?标记,否则赋空值会报错 ? 1 2 var mustNoNilValue: String = "Swift" var canNilVa ...

  10. Wd 西部数据

    西部数据 https://item.jd.com/3564471.html#none 打算买一个大硬盘记录代码片段.开发项目.开发工具.电影游戏等…… /** * 获取100天后的日子 * 用来做计划 ...