宽容他人,放过自己。

js与oc交互

Posted on By anchoriteFili

相关链接


代码相关理解


1. OC调用js中函数方法

OC中相关代码

#pragma mark oc调用js有参数方法
- (IBAction)ocCallJsHasParams:(UIButton *)sender {
    
    NSString *js = [NSString stringWithFormat:@"ocCallJsHasParamsFunction('hello','hello');"];
    [self.webView stringByEvaluatingJavaScriptFromString:js];
}

#pragma mark oc调用js无参数
- (IBAction)ocCallJsNoParams:(UIButton *)sender {
    
    NSString *js = [NSString stringWithFormat:@"ocCallJsNoParamsFunction();"];
    [self.webView stringByEvaluatingJavaScriptFromString:js];
}

js中小关代码

function ocCallJsNoParamsFunction() {
    alert("调用了了无参数按钮");
}

function ocCallJsHasParamsFunction( a, b ) {
    
    alert("输入了参数" + a + b);
}
2. js调用OC中方法

OC中相关方法

# pragma mark 此处可以拦截URL申请,OC网络申请和webview中点击事件的申请都会拦截
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *urlstr = request.URL.absoluteString;
    
    NSString *string2 = [urlstr substringWithRange:NSMakeRange(urlstr.length-3, 3)];
    NSLog(@"string2 ======= %@",string2);
    
    if ([string2 isEqualToString:@"mp4"]) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"movieUrlChange" object:self userInfo:@{@"urlStr":urlstr,@"urlType":@"movieUrl",@"name":@"电影名字"}];
    }
    return YES;
}

js中点击方法

// 切换影片方法
function qieHuanYingPian(i) {    
    var iFrame;  
    iFrame = document.createElement("iframe");  
    iFrame.setAttribute("src", movies[i].MovieUrl);  
    iFrame.setAttribute("style", "display:none;");  
    document.body.appendChild(iFrame);  
    // 发起请求后这个iFrame就没用了,所以把它从dom上移除掉  
    iFrame.parentNode.removeChild(iFrame);  
    iFrame = null;  
}
function appShareProduct(type) {
    
    if(type == 1) {
        
          document.location = "object:YQTHYL" + type;
    } 
    
    if (type == 2) {
        type = "http://mtest.lvyouquan.cn/App/TravelTogetherQRCode";
          document.location = "object:YQTHYL" + type;
    }
}