码迷,mamicode.com
首页 > Web开发 > 详细

UIWebView中Html中用JS调用OC方法及OC执行JS代码

时间:2015-06-08 14:50:36      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

原理:每次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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!