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区别