iOS中調(diào)用HTML借助WebView來顯示
方法://加載網(wǎng)頁
NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
如果想在iOS對HTML操作(增,刪,改,查):
首先要執(zhí)行webView的代理方法:
-(void)webViewDidFinishLoad:(UIWebView *)webView{}
在代理方法中執(zhí)行那些操作
#pragma mark - 操作網(wǎng)頁
-(void)webViewDidFinishLoad:(UIWebView *)webView{
// 刪除
NSString *str1 = @"var word = document.getElementById('word');";
NSString *str2 = @"word.remove();";
[webView stringByEvaluatingJavaScriptFromString:str1];
[webView stringByEvaluatingJavaScriptFromString:str2];
// 更改
NSString *str3 = @"var change = document.getElementsByClassName('change')[0];" "change.innerHTML = '好你的哦!';";
[webView stringByEvaluatingJavaScriptFromString:str3];
// 插入NSString *str4 =@"var img = document.createElement('img');"
"img.src = 'img_01.jpg';"
"img.width = '160';"
"img.height = '80';"
"document.body.appendChild(img);";
[webView stringByEvaluatingJavaScriptFromString:str4];}
在HTML中調(diào)用iOS
//加載網(wǎng)頁
NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
首先要執(zhí)行webView的代理方法:
這個代理方法,可以實時監(jiān)聽到HTML發(fā)出的事件點擊
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
}
下面是加載的HTML里面的內(nèi)容, 實現(xiàn)的是通過按鈕點擊,訪問相冊:
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<button onclick="getImage();">訪問相冊</button>
<script> function getImage(){ window.location.href = 'xmg://getImage'; } </script>
</body>
</html>
在webView的代理方法里面可以實時監(jiān)聽, 所以可以截取到xmg://getImage 這個字符串,我們只要截取最后的getImage, 然后在iOS中調(diào)用對應(yīng)的方法,就可以實現(xiàn)調(diào)用iOS中的功能, 所有實現(xiàn)HTML調(diào)用iOS,訪問相冊
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString *str = request.URL.absoluteString;
NSRange range = [str rangeOfString:@"xmg://"];
//判斷是不是以這開頭的協(xié)議
if (range.location != NSNotFound) {
//能找到 NSString *method = [str substringFromIndex:range.location + range.length];
SEL sel = NSSelectorFromString(method);
[self performSelector:sel];
}
return YES;
}
- (void)getImage{
UIImagePickerController *pickerImg = [[UIImagePickerController alloc]init];
pickerImg.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:pickerImg animated:YES completion:nil];
}
<本文轉(zhuǎn)載自 Tanyfi>