UIWebView - 使用方法总结

使用方法总结

1.创建、设置代理

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. UIWebView *webView=[[UIWebView alloc] initWithFrame:CGRectMake(020320300)];    
  2. webView.delegate = self;  

2.加载网页

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. NSURL *url=[NSURL URLWithString:@"http://www.google.com.hk"];  //创建URL  
  2. NSURLRequest *request=[[NSURLRequest alloc] initWithURL:url];  //创建NSURLRequest  
  3. [webView loadRequest:request];<span style="white-space:pre">  </span>//加载  

3.加载本地资源

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. NSURL* url = [NSURL fileURLWithPath:filePath];  <span style="white-space:pre">        </span>   //创建URL  
  2. NSURLRequest* request = [NSURLRequest requestWithURL:url];    //创建NSURLRequest  
  3. [webView loadRequest:request];     //加载  

UIWebView 还支持将一个NSString对象作为源来加载。你可以为其提供一个基础URL,来指导UIWebView对象如何跟随链接和加载远程资源:

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. [webView loadHTMLString:myHTML baseURL:[NSURL URLWithString:@"http://baidu.com"]];  

4.是否与用户交互(即用户能不能控制webView)

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. [webView setUserInteractionEnabled:YES];    

5.显示UIWebView(加载视图)

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. [self.view addSubview:webView];    

6.导航

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. [webView goBack];       //返回    
  2. [webView goForward];    //向前    
  3. [webView reload];       //重新加载数据(重载)  
  4. [webView stopLoading];  //停止加载数据(取消载入内容)  

7.自动对页面进行缩放以适应屏幕

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. webView.scalesPageToFit = YES;  

8.自动检测网页上的电话号码,单击可以拨打

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. webView.detectsPhoneNumbers = YES;    

9.UIWebView 还支持将一个NSString对象作为源来加载。你可以为其提供一个基础URL,来指导UIWebView对象如何跟随链接和加载远程资源 

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. [webView loadHTMLString:myHTML baseURL:[NSURL URLWithString:@"http://baidu.com"]];   

10.UIWebView和JS交互  

(1)在Objective-C代码中调用JS  

使用stringByEvaluatingJavaScriptFromString方法,需要等到UIWebView中的页面加载完成之后去调用。 

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. -(void) webViewDidFinishLoad:(UIWebView *)webView  
  2.     
  3.     [self.activityViewstopAnimating];    
  4.     [myWebView stringByEvaluatingJavaScriptFromString:@"function test(){ alert(123123123)}"];    
  5.     [myWebView stringByEvaluatingJavaScriptFromString:@"test();"];//调用    
  6.     

(2)在JS中调用Objective-C代码  

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //JS代码:    
  2. function sendCommand(cmd,param)  
  3.   {    
  4.      var url="testapp:"+cmd+":"+param;    
  5.      document.location = url;    
  6.   }    
  7.      function clickLink()  
  8.   {    
  9.      sendCommand("alert","你好吗?");    
  10.   }    

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //Objective-C代码:    
  2. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType   
  3.   {    
  4.         NSString *requestString = [[request URL] absoluteString];    
  5.         NSArray *components = [requestString componentsSeparatedByString:@":"];    
  6.         if ([components count] > 1 && [(NSString *)[components objectAtIndex:0] isEqualToString:@"testapp"])  
  7.         {    
  8.             if([(NSString *)[components objectAtIndex:1] isEqualToString:@"alert"])    
  9.             {    
  10.                 UIAlertView *alert = [[UIAlertView alloc]    
  11.                                       initWithTitle:@"Alert from Cocoa Touch" message:[components objectAtIndex:2]    
  12.                                       delegate:self cancelButtonTitle:nil    
  13.                                       otherButtonTitles:@"OK", nil nil nil];    
  14.                 [alert show];    
  15.             }    
  16.             return NO;    
  17.         }    
  18.         return YES;    
  19.     }    

UIWebView的委托方法  

1.web视图指示加载内容时通知。应该返回YES开始加载。导航提供的类型参数,是指请求的来源,可以是下列任何一个:

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //UIWebViewNavigationTypeLinkClicked     用户触击了一个链接    
  2. //UIWebViewNavigationTypeFormSubmitted   用户提交了一个表单    
  3. //UIWebViewNavigationTypeBackForward     用户触击前进或返回按钮    
  4. //UIWebViewNavigationTypeReload          用户触击重新加载的按钮    
  5. //UIWebViewNavigationTypeFormResubmitted 用户重复提交表单    
  6. //UIWebViewNavigationTypeOther           发生其它行为    
  7. -(BOOL)webView:(UIWebView *)webView  shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;    

2.开始加载的时候执行该方法。 

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (void)webViewDidStartLoad:(UIWebView *)webView;  //当网页视图已经开始加载一个请求后,得到通知   

3.加载完成的时候执行该方法。

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (void)webViewDidFinishLoad:(UIWebView *)webView; //当网页视图结束加载一个请求后,得到通知  

4.加载出错的时候执行该方法。  

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error; //当在请求加载中发生错误时,得到通知。会提供一个NSSError对象,以标识所发生错误类型  

UIWebView常用注意点:

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

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. -(void)webViewDidFinishLoad:(UIWebView *)webView  
  2. {  
  3.     NSString *sendJsStr = [NSString stringWithFormat:@"openFile(\"%@\")",jsDocPathStr];  
  4.     [webView stringByEvaluatingJavaScriptFromString:sendJsStr];  
  5. }  

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

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType  

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

4、为webView添加背景图片:

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. approvalWebView.backgroundColor = [UIColor clearColor];  
  2. approvalWebView.opaque=NO;//这句话很重要,webView是否是不透明的,no为透明 在webView下添加个imageView展示图片就可以了  

5、获取webView页面内容信息:

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. NSString *docStr=[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];//获取web页面内容信息,此处获取的是个json字符串  
  2. SBJsonParser *parserJson=[[[SBJsonParser alloc]init]autorelease];  
  3. NSDictionary *contentDic=[parserJson objectWithString:docStr];//将json字符串转化为字典  

6、 加载本地文件的方法:

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //第一种方法:  
  2.     NSString* path = [[NSBundle mainBundle] pathForResource:name ofType:@"html" inDirectory:@"mobile"];//mobile是根目录,name是文件名称,html是文件类型  
  3.     [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]]; //加载本地文件  
[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //第二种方法:  
  2.     NSString *resourcePath = [[NSBundle mainBundle] resourcePath];  
  3.     NSString *filePath = [resourcePath stringByAppendingPathComponent:@"mobile.html"];  
  4.     NSString *htmlstring=[[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];  
  5.     [uiwebview loadHTMLString:htmlstring baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];  

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

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];  
  2. self.filePath = [resourceDocPath stringByAppendingPathComponent:[NSString stringWithFormat:@"maydoc%@",docType]];  
  3. NSData *attachmentData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:theUrl]];  
  4. [attachmentData writeToFile:filePath atomically:YES];  
  5. NSURL *url = [NSURL fileURLWithPath:filePath];  
  6. NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];  
  7. [attachmentWebView loadRequest:requestObj];  
  8. 指定目录下的文件  
  9. NSFileManager *magngerDoc=[NSFileManager defaultManager];  
  10. [magngerDoc removeItemAtPath:filePath error:nil];  

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

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. if ([theType isEqualToString:@".txt"])  
  2. {  
  3.     //txt分带编码和不带编码两种,带编码的如UTF-8格式txt,不带编码的如ANSI格式txt  
  4.     //不带的,可以依次尝试GBK和GB18030编码  
  5.     NSString* aStr = [[NSString alloc] initWithData:attachmentData encoding:NSUTF8StringEncoding];  
  6.     if (!aStr)  
  7.     {  
  8.      //用GBK进行编码  
  9.      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语言进行排版  
  17.     NSString* responseStr = [NSString stringWithFormat:@"""""""""%@""/pre>""""",aStr];  
  18.     [attachmentWebView loadHTMLString:responseStr baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];  
  19.     return;  
  20. }  

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

(1)、 Loading a local PDF file into the web view

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];  
  4.     //从本地加载  
  5.     NSString *thePath = [[NSBundle mainBundle] pathForResource:@"iPhone_User_Guide" ofType:@"pdf"];  
  6.     if (thePath)  
  7.     {  
  8.     NSData *pdfData = [NSData dataWithContentsOfFile:thePath];  
  9.     [(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. }  

(2)、The web-view delegate managing network loading

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (void)webViewDidStartLoad:(UIWebView *)webView  
  2. {  
  3.     // starting the load, show the activity indicator in the status bar  
  4.     [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;  
  5. }  
  6.   
  7. - (void)webViewDidFinishLoad:(UIWebView *)webView  
  8. {  
  9.     // finished loading, hide the activity indicator in the status bar  
  10.     [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;  
  11. }  
  12.   
  13. - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error  
  14. {  
  15.     // load error, hide the activity indicator in the status bar  
  16.     [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;  
  17.   
  18.     // report the error inside the webview  
  19.     NSString* errorString = [NSString stringWithFormat:  
  20.     @"An error occurred: 
  21.     %@",  
  22.     error.localizedDescription];  
  23.     [self.myWebView loadHTMLString:errorString baseURL:nil];  
  24. }  

(3)、Stopping a load request when the web view is to disappear

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (void)viewWillDisappear:(BOOL)animated  
  2. {  
  3.     if ( [self.myWebView loading] )  
  4.     {  
  5.      [self.myWebView stopLoading];  
  6.     }  
  7.     self.myWebView.delegate = nil// disconnect the delegate as the webview is hidden  
  8.     [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;  
  9. }  

/************/
引用自苹果官方文档(displaying web content)

10、查找webView中的scrollview:

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (void) addScrollViewListener  
  2. {  
  3.     UIScrollView* currentScrollView;  
  4.     for (UIView* subView in self.webView.subviews)   
  5.     {  
  6.        if ([subView isKindOfClass:[UIScrollView class]])   
  7.        {  
  8.         currentScrollView = (UIScrollView*)subView;  
  9.         currentScrollView.delegate = self;  
  10.        }  
  11.     }  
  12. }  

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

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (void)clearBackgroundWithColor:(UIColor*)color  
  2. {  
  3.      //去掉webview的阴影  
  4.      self.backgroundColor = color;  
  5.      for (UIView* subView in [self subviews])  
  6.      {  
  7.        if ([subView isKindOfClass:[UIScrollView class]])   
  8.        {  
  9.           for (UIView* shadowView in [subView subviews])  
  10.           {  
  11.              if ([shadowView isKindOfClass:[UIImageView class]])  
  12.              {  
  13.                [shadowView setHidden:YES];  
  14.              }  
  15.           }  
  16.        }  
  17.     }  
  18. }  

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

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. -(void)webViewDidFinishLoad:(UIWebView *)webView  
  2. {  
  3.     [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout = 'none';"];  
  4. }  

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

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType  
  2. {  
  3.     if (navigationType==UIWebViewNavigationTypeLinkClicked)   
  4.     {  
  5.       return NO;  
  6.     }  
  7.     else   
  8.     {  
  9.       return YES;  
  10.     }  
  11. }  

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

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. -(void)deleteCookieForDominPathStr:(NSString *)thePath  
  2. {  
  3.     //删除本地cookie,thePath为cookie路径通过打印cookie可知道其路径  
  4.     for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])   
  5.     {  
  6.         if([[cookie domain] isEqualToString:thePath])   
  7.         {  
  8.           [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];  
  9.         }  
  10.     }  
  11. }  

16、在UIWebView中使用flashScrollIndicators

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

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. for (id subView in [webView subviews])  
  2. {   
  3.     if ([subView respondsToSelector:@selector(flashScrollIndicators)])  
  4.     {  
  5.         [subView flashScrollIndicators];  
  6.     }  
  7. }  
上述代码片段可以到webViewDidFinishLoad回调中使用,加载完网页内容后flash显示滚动标识。

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

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

①.使用sizeThatFits方法。

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  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

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (void)webViewDidFinishLoad:(UIWebView *)webView  
  2. {  
  3.    CGRect frame = webView.frame;  
  4.    NSString *fitHeight = [webview stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"];  
  5.    frame.size.height = [fitHeight floatValue];  
  6.    webView.frame = frame;  
  7. }  

总结:

首先 对IOS开发中的UIWebView控件的基本使用进行初步的详解,提到了创建、设置属性、设置背景、怎么样加载网页内容等一系列的基础点,然后阐述使用UIWebView控件时常用用注意点,经常需要用到的地方,需要注意的地方,使得对开发ios APP混合模式的桥梁---UIWebView控件更加的了解、熟悉。UIWebView既能够加载服务器提供的URI,又能够加载本地的资源文件,还能够加载服务器返回的网页界面代码,可想而知UIWebView是多么强大的一控件桥梁,以后在开发中使用到的地方会越来越多。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值