标签:
原理:每次webview执行跳转时都会被iOS给拦截,执行下面函数获得系统允许。
因此可以根据跳转信息转给系统,执行相应功能,比如打开相册等。
// 网页中的每一个请求都会被触发
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
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; } </script> </head> <body> <h1 onclick="getInfo(‘openMyAlbum‘)">打开相册</h1> <br> <h1 onclick="getInfo(‘openMyCamera‘)">打开相机</h1> </body> </html>
OC:
#import "ViewController.h" @interface ViewController (){ UIWebView *webView; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self.view setBackgroundColor:[UIColor lightGrayColor]]; webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))]; NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8888/testhtml.html"]]; [self.view addSubview: webView]; [webView loadRequest:request]; [webView setDelegate:self]; // Do any additional setup after loading the view, typically from a nib. } - (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]; } @end
UIWebView中Html中用JS调用OC方法及OC执行JS代码
标签:
原文地址:http://www.cnblogs.com/rayshen/p/4560728.html