[iOS Hybrid實踐:UIWebView中Html中用JS調用OC方法,OC執行JS代碼]

原理:html

1.JS調用OCgit

每次webview執行跳轉時都會被iOS給攔截,執行下面函數得到系統容許。github

所以能夠根據跳轉信息轉給系統,執行相應功能,好比打開相冊等。web

// 網頁中的每個請求都會被觸發
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

2.OC調用JS:經過webview執行js函數實現app

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

HTML:ide

<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(0,22, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)-66)];
    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(0, CGRectGetHeight(self.view.bounds)-44, 88, 44)];
    [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(0, 2,  CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)-66)];
    [view setTag:108];
    [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:108];
    [view removeFromSuperview];
    NSLog(@"webViewDidFinishLoad");
    
}
- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [activityIndicator stopAnimating];
    UIView *view = (UIView*)[self.view viewWithTag:108];
    [view removeFromSuperview];
    NSLog(@"didFailLoadWithError:%@", error);
}

 

github:https://github.com/rayshen/OChybridTestpost

相關文章
相關標籤/搜索