[iOS Hybrid实践:UIWebView中Html中用JS调用OC方法,OC执行JS代码]

时间:2022-06-01 20:39:46

原理:

1.JS调用OC

每次webview执行跳转时都会被iOS给拦截,执行下面函数获得系统允许。

因此可以根据跳转信息转给系统,执行相应功能,比如打开相册等。

// 网页中的每一个请求都会被触发
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

2.OC调用JS:通过webview执行js函数实现

[webView stringByEvaluatingJavaScriptFromString:@"postStr();"];

HTML:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="UTF-8"/>
<title>HTML中用JS调用OC方法</title>
<script>
function getInfo(name)
{
window.location = "/getInfo/"+name;
} function postStr(){
return "I am script";
}
</script>
</head>
<body>
<h1 onclick="getInfo('openMyAlbum')">打开相册</h1>
<br>
<h1 onclick="getInfo('openMyCamera')">打开相机</h1>
</body>
</html>

OC:

#import "ViewController.h"

@interface ViewController (){
UIWebView *webView;
UIActivityIndicatorView *activityIndicator;
} @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor lightGrayColor]];
webView = [[UIWebView alloc] initWithFrame:CGRectMake(,, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)-)];
NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://dong14.sinaapp.com/testhtml.html"]];
[self.view addSubview: webView];
[webView loadRequest:request];
[webView setDelegate:self];
// Do any additional setup after loading the view, typically from a nib. UIButton *clkbtn=[[UIButton alloc]initWithFrame:CGRectMake(, CGRectGetHeight(self.view.bounds)-, , )];
[clkbtn setTitle:@"调用JS" forState:UIControlStateNormal];
[clkbtn setBackgroundColor:[UIColor redColor]];
[clkbtn addTarget:self action:@selector(jsclk) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:clkbtn];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} // 网页中的每一个请求都会被触发
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{ // 每次跳转时候判断URL
if([request.mainDocumentURL.relativePath isEqualToString:@"/getInfo/openMyAlbum"])
{
NSLog(@"openMyAlbum");
[self openMyAlbum];
return NO;
} // 每次跳转时候判断URL
if([request.mainDocumentURL.relativePath isEqualToString:@"/getInfo/openMyCamera"])
{
NSLog(@"openMyCamera");
[self openMyCamera];
return NO;
} return YES;
} -(void)openMyAlbum
{
UIImagePickerController *vc = [[UIImagePickerController alloc]init];
vc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:vc animated:YES completion:nil];
} -(void)openMyCamera
{
UIImagePickerController *vc = [[UIImagePickerController alloc]init];
vc.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:vc animated:YES completion:nil];
} -(void)jsclk{
NSString *str = [webView stringByEvaluatingJavaScriptFromString:@"postStr();"];
NSLog(@"JS返回值:%@",str);
} - (void) webViewDidStartLoad:(UIWebView *)webView
{
//创建UIActivityIndicatorView背底半透明View
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(, , CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)-)];
[view setTag:];
[view setBackgroundColor:[UIColor blackColor]];
[view setAlpha:0.5];
[self.view addSubview:view]; activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
[activityIndicator setCenter:view.center];
[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
[view addSubview:activityIndicator]; [activityIndicator startAnimating];
NSLog(@"webViewDidStartLoad");
}
- (void) webViewDidFinishLoad:(UIWebView *)webView
{
[activityIndicator stopAnimating];
UIView *view = (UIView*)[self.view viewWithTag:];
[view removeFromSuperview];
NSLog(@"webViewDidFinishLoad"); }
- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[activityIndicator stopAnimating];
UIView *view = (UIView*)[self.view viewWithTag:];
[view removeFromSuperview];
NSLog(@"didFailLoadWithError:%@", error);
}

github:https://github.com/rayshen/OChybridTest