本文主要記錄UIWebView三方面內容:
1、基本的載入網頁連結或檔案;
2、網頁js呼叫原生,也就是Cordova混合架構的原理;
3、原生呼叫js程式;
- 原生部分主要程式碼:
@implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; self.title = @"WebView Test"; webview_ = [[UIWebView alloc]init];
webview_.frame = self.view.bounds; webview_.delegate = self; //自動縮放頁面
webview_.scalesPageToFit = YES; //webview提供的導航方法如下:
// [webView_ goBack];
// [webview_ goForward];
// [webview_ reload];
// [webview_ stopLoading]; [self.view addSubview:webview_];
} -(void)viewDidAppear:(BOOL)animated{
NSLog(@"viewDidAppear");
// 載入普通URL
// NSURL* url;
// http請求需要在info.plist資訊中增加如下配置:
// <key>NSAppTransportSecurity</key>
// <dict>
// <key>NSAllowsArbitraryLoads</key>
// <true/>
// </dict>
// url = [[NSURL alloc]initWithString:@"http://www.baidu.com/"];
// [webview_ loadRequest:[NSURLRequest requestWithURL:url]]; [self loadHTMLFile:@"hello.html"]; } //載入一個本地html
- (void)loadHTMLFile:(NSString*)filename {
NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@""];
NSData* data = [NSData dataWithContentsOfFile:path];
[webview_ loadData:data MIMEType:@"text/html" textEncodingName:@"utf-8" baseURL:nil];
} //javascript呼叫原生方法,也是Cordova混合架構的原理
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(@"shouldStartLoadWithRequest");
NSString *url = request.URL.absoluteString;
NSLog(@"%@", url);
if([url hasSuffix:@"iostest"]){
return NO;
}
return YES;
} - (void)webViewDidFinishLoad:(UIWebView *)webView {
//執行javascript語句
NSLog(@"webViewDidFinishLoad");
NSString *js = @"test2('hello')";
[webview_ stringByEvaluatingJavaScriptFromString:js];
} @end
- 網頁部分
<html>
<head>
<script type="text/javascript">
var iFrame;
iFrame = document.createElement('iframe');
iFrame.style.display = 'none';
document.documentElement.appendChild(iFrame);
//建立一個iFrame,並修改其src,此時IOS中的shouldStartLoadWithRequest會被回撥 function test1(){
iFrame.src = "iostest";
} function test2(input){
alert(input);
} </script>
</head> <body>
<p>This is Test Page.</p>
<button onclick="test1()">hello</button>
</body>
</html>