Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 481|回复: 0

[默认分类] UIWebView加载本地HTML5文件

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2018-5-24 15:45:45 | 显示全部楼层 |阅读模式

      UIWebView加载本地HTML5文件
      
       一.准备HTML文件及其资源文件
       使用UIWebView加载本地的HTML文件 index.html,在index.html中引用了本地的图片、CSS文件、JS文件以及外部的图片。
    index.html内容如下
    1. [code]<html>
    2.     <head>
    3.         <link href="index.css" rel="stylesheet" type="text/css">
    4.         <script type="text/javascript"language="javascript"src="index.js">
    5.     </head>
    6.     <body>
    7.         <p>This is local Image</p>
    8.         <img src="Smiley.png" width="50" height="50" />
    9.         <hr/>
    10.         <p>this is local image from CSS.</p>
    11.         <div id="myimage"> </div>
    12.         <hr/>
    13.         <p>this is external image.</p>
    14.         <img src="http://imglf9.ph.126.net/F37NyhuzmvHJChMARbFmHA==/1010495166409149719.jpg" width="300" height="200" />
    15.     </body>
    16. </html>
    复制代码
    [/code]
       HTML中会显示3张图片,第一张是html从本地读取的图片,第二张是通过CSS从本地读取的图片,第三张是通过绝对地址从外部读取的图片。
    index.css文件内容如下:
    1. [code]body {
    2.     padding: 0px;
    3.     margin: 0px;
    4. }
    5. p {
    6.     font-size: 15px;
    7.     color: #808080;
    8.     font-family: Arial, Helvetica, sans-serif;
    9. }  
    10. #myimage {
    11.     background-image: url(SmallSmiley.png);
    12.     background-repeat: repeat-x;
    13. }
    复制代码
    [/code]
       index.js文件内容为:
    1. [code]function rewrite()
    2. {
    3.     document.write("This text was written by an external script!")
    4. }
    复制代码
    [/code]
       index.js
    还有引用到了两个本地图片文件:
    SmallSmiley.png
    Smiley.png
       二.加载本地HTML文件
       将html文件及相关资源添加到项目中

    需要注意的是,把js文件加入到项目时会默认将其当做需要编译的代码,需要在TARGETS->Build Phases中的”Compile Sources”中找到该js文件,并将其移到上面的Copy Bundle Resources中。

       然后在代码中可以用两种方法加载。
    1.第一种方式,使用loadRequest:方法加载本地文件NSURLRequest
    1. [code]NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    2. NSURL* url = [NSURL fileURLWithPath:path];
    3. NSURLRequest* request = [NSURLRequest requestWithURL:url] ;
    4. [webView loadRequest:request];
    复制代码
    [/code]
       2.第二种方式,使用loadHTMLString:baseURL:加载HTML字符串
    1. [code]NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
    2. NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    3. NSString *html = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    4. [webView loadHTMLString:html baseURL:baseURL];
    复制代码
    [/code]
       加载后的显示效果如下,本地图片,CSS加载的本地图片,以及外部图片都可以正常显示。

       在HTML页面加载完毕后,我们可以使用UIWebViewstringByEvaluatingJavaScriptFromString:方法执行javascript语句。如下:
    1. [code]- (void)webViewDidFinishLoad:(UIWebView *)webView{
    2.     [webView stringByEvaluatingJavaScriptFromString:@"rewrite();"];
    3. }
    复制代码
    [/code]
       执行js代码后,页面显示就变成了

       三.关于baseURL
       loadHTMLString:baseURL:方法的第二个参数是baseURL,baseURL即HTML字符串中引用到资源的查找路径,没有引用外部资源时,可以直接传nil;若引用了外部资源,一般情况下使用mainBundle的路径即可,即
    1. [code]NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
    复制代码
    [/code]
       这是因为,Xcode项目中的文件路径都是虚拟的,在APP中实际不存在,即在APP中,几乎所有的文件都可以从mainBundle根目录下直接访问,当然,例外总是存在的。
       在将文件/文件夹加入到项目时,有这样两个选项“Create Folder References for any added folders”和“Recursively create groups for any added folders”。

    默认情况下为第一种,即所有加入到项目的文件都会在mainBundle根路径下,即不管加入项目的文件的目录结构如何,在APP中都可以通过mainBundlePath/filename来访问到;如果采用第二种方式,则就会保留相对路径,需要通过mainBundlePath/path/filename来访问。通过这两种方式到项目的文件夹显示具有不同的颜色,如下

    images1目录是使用“Create Folder References for any added folders”增加的目录,images2目录是使用“Recursively create groups for any added folders”增加的目录。
       获取images1目录下文件的代码如下:
    1. [code]NSString* image1Path = [[NSBundle mainBundle] pathForResource:@"image1"ofType:@"jpg"];
    2. NSString* image11Path = [[NSBundle mainBundle] pathForResource:@"image11"ofType:@"jpg"];
    复制代码
    [/code]
       images1和images11目录实际是不存在的,下面代码返回的路径都是nil
    1. [code]NSString* images1Dir = [[NSBundle mainBundle] pathForResource:@"images1"ofType:nil];
    2. NSString* images11Dir = [[NSBundle mainBundle] pathForResource:@"images11"ofType:nil];
    复制代码
    [/code]
       对于images2目录以及目录下的文件路径,其在APP中仍然保持了目录关系,就不能用上述方法获取,而且目录路径是真实存在的,应该使用的代码如下:
    1. [code]NSString* images2Path = [[NSBundle mainBundle] pathForResource:@"image2"ofType:@"jpg"inDirectory:@"images2"];
    2. NSString* image22Path = [[NSBundle mainBundle] pathForResource:@"image22"ofType:@"jpg"inDirectory:@"images2/images22"];
    3. NSString* images2Dir = [[NSBundlemainBundle] pathForResource:@"images2"ofType:nil];
    4. NSString* images2Dir = [[NSBundle mainBundle] pathForResource:@"images22"ofType:nilinDirectory:@"images2"];
    复制代码
    [/code]
       还有一种比较特殊的目录是以.bundle为后缀的目录,将其加入到项目是不管选择的是哪个选项,其都会保持其目录结构。

    对子bundle的访问,可以通过同images2目录相同的方法访问,但一般情况下是先获取到子Bundle,再通过子Bundle获取到其里面的资源。
    1. [code]NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"images" ofType:@"bundle"]];
    2. NSString* imagebPath = [bundle pathForResource:@"imageb"ofType:@"jpg"];
    3. NSString* imagebbPath = [bundle pathForResource:@"imagebb"ofType:@"jpg" inDirectory:@"imagesb"];
    复制代码
    [/code]
    1. [code]
    复制代码
    [/code]
    1. [code]////////
    复制代码
    [/code]
    1. [code]
    复制代码
    [/code]
       ios和android都提供了有关webview和javascript通讯的功能,这就使开发者根据手机的系统展示适合手机的界面,是界面开发更加简单。
      我的原型主要实现通过UIWebView展示本地的html、css、javascript文件,并且和ios互相通讯,用来展示数据。
      下面是我实现的一个简单demo,界面效果如下:
      
      点击连接调用ios中的提醒功能:
      
      实现过程:
      
       首先创建一个工程,ipad.web1,编译运行成功。
       实现webview的代码:
      
       
       
       #import <UIKit/UIKit.h>
       @interface ipad_web1ViewController : UIViewController  <UIWebViewDelegate>{      IBOutlet UIWebView *myWebView;  }  @property (nonatomic,retain) UIWebView *myWebView;  @end
      
      相应的.m文件:
       #import "ipad_web1ViewController.h"
       @implementation ipad_web1ViewController  @synthesize myWebView;  - (void)viewDidLoad {      [super viewDidLoad];      self.myWebView.delegate=self;      NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];      [myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath: path]]];  }  - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {      return YES;  }
       - (void)didReceiveMemoryWarning {      [super didReceiveMemoryWarning];  }
       - (void)viewDidUnload {      self.myWebView=nil;  }
       - (void)dealloc {      [self.myWebView release];      [super dealloc];  }  #pragma mark –  #pragma mark UIWebViewDelegate  - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {      if ( [request.mainDocumentURL.relativePath isEqualToString:@"/click/false"] ) {             NSLog( @"not clicked" );          return false;      }      if ( [request.mainDocumentURL.relativePath isEqualToString:@"/click/true"] ) {        //the image is clicked, variable click is true          NSLog( @"image clicked" );          UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"JavaScript called"                                                       message:@"You’ve called iPhone provided control from javascript!!" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];          [alert show];          [alert release];          return false;      }      return true;  }  - (void)webViewDidStartLoad:(UIWebView *)webView  {      NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];      NSLog(@"title11=%@",title);  }  - (void)webViewDidFinishLoad:(UIWebView *)webView  {      NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];      NSLog(@"title=%@",title);      //添加数据     [myWebView stringByEvaluatingJavaScriptFromString:@"var field = document.getElementById("field_2");"        "field.value="Multiple statements - OK";"];      //[myWebView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement("script");"   //     "script.type = "text/javascript";"   //     "script.text = \"function myFunction() { "   //     "var field = document.getElementById("field_3");"   //     "field.value="Calling function - OK";"   //     "}\";"   //     "document.getElementsByTagName("head")[0].appendChild(script);"];   //     //    [myWebView stringByEvaluatingJavaScriptFromString:@"myFunction();"];   }  - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error  {  }  @end
      
      
       最后在Interface Builder中添加UIwebView控件,并且和相应的实体相关联。
      
          NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];      NSLog(@"title=%@",title);
      
      主要是获取html文件的title名字。
       [myWebView stringByEvaluatingJavaScriptFromString:@"var field = document.getElementById("field_2");"        "field.value="Multiple statements - OK";"];
      
      添加相应的表单信息。
      
       接下来添加index.html文件:
      
       <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <html xmlns="http://www.w3.org/1999/xhtml">  <head>      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />      <title>How to build an iPhone website</title>      <meta name="author" content="will" />      <meta name="copyright" content="copyright 2008 www.engageinteractive.co.uk" />      <meta name="description" content="Welcome to engege interactive on the iPhone!" />      <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">      <link rel="apple-touch-icon" href="images/template/engage.png"/>      <style type="text/css">          @import url("layout.css");      </style>      <script type="text/javascript" src="test.js"></script>     </head>  <body>  <h1>测试</h1>     <center><a href="javascript:void(0)" onMouseDown="imageClicked()">click me</a></center>     <form>         <input id="field_1" type="text" name="value" /><br/><br/><br/>         <input id="field_2" type="text" name="value" /><br/><br/><br/>         <input id="field_3" type="text" name="value" /><br/><br/><br/>       </form>   </body>  </html>
      
      
       添加相应的css文件:
      
       body {      background-color: #F2F5A9;  }
      
      
       添加相应的js文件:
      
       function imageClicked(){      var clicked=true;      window.location="/click/"+clicked;  }
      
      运行,点击连接应该不出相应的对话框,说明相应的javascript没有生效。修改办法是打开targets,点击ipad.web1,移动相应的test.js文件到下图即可。
         源代码:http://easymorse-iphone.googlecode.com/svn/trunk/ipad.web1/
    1. [code]
    复制代码
    [/code]
      

      
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-5-16 12:39 , Processed in 0.425497 second(s), 48 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表