iOS中调用HTML借助WebView来显示
方法://加载网页
NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
如果想在iOS对HTML操作(增,删,改,查):
首先要执行webView的代理方法:
-(void)webViewDidFinishLoad:(UIWebView *)webView{}
在代理方法中执行那些操作
#pragma mark - 操作网页
-(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中调用iOS
//加载网页
NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
首先要执行webView的代理方法:
这个代理方法,可以实时监听到HTML发出的事件点击
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
}
下面是加载的HTML里面的内容, 实现的是通过按钮点击,访问相册:
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<button onclick="getImage();">访问相册</button>
<script> function getImage(){ window.location.href = 'xmg://getImage'; } </script>
</body>
</html>
在webView的代理方法里面可以实时监听, 所以可以截取到xmg://getImage 这个字符串,我们只要截取最后的getImage, 然后在iOS中调用对应的方法,就可以实现调用iOS中的功能, 所有实现HTML调用iOS,访问相册
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString *str = request.URL.absoluteString;
NSRange range = [str rangeOfString:@"xmg://"];
//判断是不是以这开头的协议
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];
}
<本文转载自 Tanyfi>