在iOS中調(diào)用HTML
iOS中調(diào)用HTML借助WebView來顯示
- 方法:
//加載網(wǎng)頁(yè)
NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
```
- 如果想在iOS對(duì)HTML操作(增,刪,改,查):
- 首先要執(zhí)行webView的代理方法:
```objc
-(void)webViewDidFinishLoad:(UIWebView *)webView{}
```
- 在代理方法中執(zhí)行那些操作
```objc
#pragma mark - 操作網(wǎng)頁(yè)
-(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)頁(yè)
NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
```
- 首先要執(zhí)行webView的代理方法:
```objc
這個(gè)代理方法,可以實(shí)時(shí)監(jiān)聽到HTML發(fā)出的事件點(diǎn)擊
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{}
```
下面是加載的HTML里面的內(nèi)容, 實(shí)現(xiàn)的是通過按鈕點(diǎn)擊,訪問相冊(cè):
```objc
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<button onclick="getImage();">訪問相冊(cè)</button>
<script>
function getImage(){
window.location.href = 'xmg://getImage';
}
</script>
</body>
</html>
在webView的代理方法里面可以實(shí)時(shí)監(jiān)聽, 所以可以截取到xmg://getImage 這個(gè)字符串,我們只要截取最后的getImage, 然后在iOS中調(diào)用對(duì)應(yīng)的方法,就可以實(shí)現(xiàn)調(diào)用iOS中的功能, 所有實(shí)現(xiàn)HTML調(diào)用iOS,訪問相冊(cè)
-(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];
}```