OC与js混合开发

李xu

 

OC与js混合开发

 

在iOS开发中,大多必然会用到UIWebView,所以我们有必要去研究oc与js的相互调用。

若在app中加载的webView界面进行交互,需要在移动端得到响应,并且进行传值,使oc的代码(方法)得到触发,那么请参照下面的代码实现。

 

首先在js代码中需要有如下代码

js调用OC

<script type="text/javascript">

function judge() {

window.location.href = "objc://jsToOC#param#李xu#param#http://www.baidu.com";

<!-- "李xu"为传递给oc方法的第一个参数, "http://www.baidu.com"为第二个参数 -->

}

</script>

<button onclick="judge()">点我调用OC</button> 

 

然后在OC代码中加入如下代码即可

#pragma mark -- UIWebViewDelegate委托定义方法

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{

    NSString *path =  [[request URLabsoluteString];

    if ([[UIDevice currentDevice].systemVersion doubleValue] >= 7.0) {

        path = [path stringByRemovingPercentEncoding];

    }else{

        path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    }

    

    if ([path hasPrefix:@"ios"]||[path hasPrefix:@"objc"]) {

        NSString *method = [path substringFromIndex:@"objc://".length];

        NSArray *sels = [method componentsSeparatedByString:@"#param#"];

        SEL todoM;

        if (sels.count>1) {

            todoM = NSSelectorFromString([NSString stringWithFormat:@"%@:",sels[0]]);

            NSMutableArray *params = [NSMutableArray array];

            for (int i=1; i<sels.count; i++) {

                [params addObject:sels[i]];

            }

            if ([self respondsToSelector:todoM]) {

                [self performSelector:todoM withObject:params afterDelay:0];

            }

        }else if(sels.count==1){

            todoM = NSSelectorFromString([NSString stringWithString:sels[0]]);

            if ([self respondsToSelector:todoM]) {

                [self performSelector:todoM withObject:nil afterDelay:0];

            }

        }

        return NO;

    }

    

    return YES;

}

//触发方法

- (void)jsToOC:(NSArray *)params

{

    NSLog(@"%@", params);

/*    

 LXHyperlinkController *vc = [[LXHyperlinkController allocinit];

    vc.title = params[0];

    vc.url = params[1];

    [self.navigationController pushViewController:vc animated:YES];

*/

}

 

这样当点击按钮后OC方法 “jsToOC:” 会得到触发,从而实现了OC与JS的混合开发

 

 

 

 

 
原文地址:https://www.cnblogs.com/hllak/p/4347264.html