UIWebView加載本地HTML5文件
一.準(zhǔn)備HTML文件及其資源文件
使用UIWebView加載本地的HTML文件 index.html,在index.html中引用了本地的圖片崇堰、CSS文件、JS文件以及外部的圖片。index.html內(nèi)容如下
<html> <head> <link href="index.css" rel="stylesheet" type="text/css"> <script type="text/javascript"language="javascript"src="index.js"> </head> <body> <p>This is local Image</p>
![image](http://wangjun.easymorse.com/wp-content/uploads/2010/11/image_thumb.png)
<p>this is local image from CSS.</p> <div id="myimage"> </div>
<p>this is external image.</p>
![image](http://wangjun.easymorse.com/wp-content/uploads/2010/11/image_thumb1.png)
HTML中會顯示3張圖片晦溪,第一張是html從本地讀取的圖片尤溜,第二張是通過CSS從本地讀取的圖片仪召,第三張是通過絕對地址從外部讀取的圖片敷搪。index.css文件內(nèi)容如下:
body { padding: 0px; margin: 0px;}p { font-size: 15px; color: #808080; font-family: Arial, Helvetica, sans-serif;} #myimage { background-image: url(SmallSmiley.png); background-repeat: repeat-x;}
index.js文件內(nèi)容為:
function rewrite(){ document.write("This text was written by an external script!")}
index.js還有引用到了兩個本地圖片文件:SmallSmiley.png
Smiley.png![Smiley](http://www.winddisk.com/wp-content/uploads/2012/09/Smiley.png)
二.加載本地HTML文件
將html文件及相關(guān)資源添加到項目中
![localhtml](http://www.winddisk.com/wp-content/uploads/2012/09/localhtml.png)
![CopyBundleResources](http://www.winddisk.com/wp-content/uploads/2012/09/CopyBundleResources.png)
然后在代碼中可以用兩種方法加載矩距。1.第一種方式,使用loadRequest:方法加載本地文件NSURLRequest
NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];NSURL* url = [NSURL fileURLWithPath:path];NSURLRequest* request = [NSURLRequest requestWithURL:url] ;[webView loadRequest:request];
2.第二種方式,使用loadHTMLString:baseURL:加載HTML字符串
NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];NSString *html = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];[webView loadHTMLString:html baseURL:baseURL];
加載后的顯示效果如下,本地圖片,CSS加載的本地圖片拗盒,以及外部圖片都可以正常顯示。
在HTML頁面加載完畢后锥债,我們可以使用UIWebView的stringByEvaluatingJavaScriptFromString:方法執(zhí)行JavaScript語句陡蝇。如下:
- (void)webViewDidFinishLoad:(UIWebView *)webView{ [webView stringByEvaluatingJavaScriptFromString:@"rewrite();"];}
三.關(guān)于baseURL
loadHTMLString:baseURL:方法的第二個參數(shù)是baseURL,baseURL即HTML字符串中引用到資源的查找路徑哮肚,沒有引用外部資源時登夫,可以直接傳nil;若引用了外部資源,一般情況下使用mainBundle的路徑即可允趟,即
NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
這是因為,Xcode項目中的文件路徑都是虛擬的恼策,在APP中實際不存在,即在APP中潮剪,幾乎所有的文件都可以從mainBundle根目錄下直接訪問涣楷,當(dāng)然,例外總是存在的抗碰。
在將文件/文件夾加入到項目時狮斗,有這樣兩個選項“Create Folder References for any added folders”和“Recursively create groups for any added folders”。
![addfolder](http://www.winddisk.com/wp-content/uploads/2012/09/addfolder.png)
獲取images1目錄下文件的代碼如下:
NSString* image1Path = [[NSBundle mainBundle] pathForResource:@"image1"ofType:@"jpg"];NSString* image11Path = [[NSBundle mainBundle] pathForResource:@"image11"ofType:@"jpg"];
images1和images11目錄實際是不存在的,下面代碼返回的路徑都是nil
NSString* images1Dir = [[NSBundle mainBundle] pathForResource:@"images1"ofType:nil];NSString* images11Dir = [[NSBundle mainBundle] pathForResource:@"images11"ofType:nil];
對于images2目錄以及目錄下的文件路徑,其在APP中仍然保持了目錄關(guān)系祷肯,就不能用上述方法獲取沉填,而且目錄路徑是真實存在的,應(yīng)該使用的代碼如下:
NSString* images2Path = [[NSBundle mainBundle] pathForResource:@"image2"ofType:@"jpg"inDirectory:@"images2"];NSString* image22Path = [[NSBundle mainBundle] pathForResource:@"image22"ofType:@"jpg"inDirectory:@"images2/images22"];NSString* images2Dir = [[NSBundlemainBundle] pathForResource:@"images2"ofType:nil];NSString* images2Dir = [[NSBundle mainBundle] pathForResource:@"images22"ofType:nilinDirectory:@"images2"];
還有一種比較特殊的目錄是以.bundle為后綴的目錄,將其加入到項目是不管選擇的是哪個選項佑笋,其都會保持其目錄結(jié)構(gòu)翼闹。
對子bundle的訪問,可以通過同images2目錄相同的方法訪問蒋纬,但一般情況下是先獲取到子Bundle,再通過子Bundle獲取到其里面的資源猎荠。NSBundle bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"images" ofType:@"bundle"]];NSString imagebPath = [bundle pathForResource:@"imageb"ofType:@"jpg"];NSString* imagebbPath = [bundle pathForResource:@"imagebb"ofType:@"jpg" inDirectory:@"imagesb"];
////////
iOS和Android都提供了有關(guān)webview和javascript通訊的功能,這就使開發(fā)者根據(jù)手機的系統(tǒng)展示適合手機的界面蜀备,是界面開發(fā)更加簡單关摇。
我的原型主要實現(xiàn)通過UIWebView展示本地的html、css碾阁、javascript文件输虱,并且和ios互相通訊,用來展示數(shù)據(jù)脂凶。
下面是我實現(xiàn)的一個簡單demo宪睹,界面效果如下:
點擊連接調(diào)用ios中的提醒功能:
![image](http://wangjun.easymorse.com/wp-content/uploads/2010/11/image_thumb1.png)
實現(xiàn)過程:
首先創(chuàng)建一個工程,ipad.web1蚕钦,編譯運行成功亭病。
實現(xiàn)webview的代碼:
import <UIKit/UIKit.h>
@interface ipad_web1ViewController : UIViewController <UIWebViewDelegate>{ IBOutlet UIWebView *myWebView; } @property (nonatomic,retain) UIWebView *myWebView; @end
相應(yīng)的.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); ** //添加數(shù)據(jù) **[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控件,并且和相應(yīng)的實體相關(guān)聯(lián)冠桃。
*NSString title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"]; NSLog(@"title=%@",title);
主要是獲取html文件的title名字命贴。
[myWebView stringByEvaluatingJavaScriptFromString:@"var field = document.getElementById('field_2');" "field.value='Multiple statements - OK';"];
添加相應(yīng)的表單信息道宅。
接下來添加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" />
<input id="field_2" type="text" name="value" />
<input id="field_3" type="text" name="value" />
</form> </body> </html>
添加相應(yīng)的css文件:
body { background-color: #F2F5A9; }
添加相應(yīng)的js文件:
function imageClicked(){ var clicked=true; window.location="/click/"+clicked; }
運行食听,點擊連接應(yīng)該不出相應(yīng)的對話框,說明相應(yīng)的javascript沒有生效污茵。修改辦法是打開targets樱报,點擊ipad.web1,移動相應(yīng)的test.js文件到下圖即可泞当。