访次: AmazingCounters.com 次

webview的使用以及js调用OC传参

webview如何想要js和oc交互,需要使用代理方法 ,并且需要和后台协定规则

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

    NSString *url = request.URL.absoluteString;

     NSLog(@"========%@",url);

    NSString *urlString=request.URL.absoluteString;

    //我们制定了一个协议,调用oc的方法都以hq://开头,后边跟着方法名

    NSString *scheme=@"icocos:///";

    //如果是我们自定义的协议hq://call

    if ([urlString hasPrefix:scheme]) {

        //取出scheme后边的路径

        NSString *path=[urlString substringFromIndex:scheme.length];

        //根据?区分出方法名  参数

        NSArray *array=[path componentsSeparatedByString:@"?"];

        NSLog(@"%@",array);

        NSString *methodName=array.firstObject;

        if (array.count == 2) {

          NSString *str = [array.lastObject stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

       NSDictionary *dict = [[NSString alloc] dictionaryWithJsonString:str];

            [[NSUserDefaults standardUserDefaults]setObject:dict forKey:@"Wxpaydict"];

        }

        NSLog(@"-----------%@",methodName);

        SEL method = NSSelectorFromString(methodName);

                [self performSelector:method];

        return NO;

    }

    return YES;

}

 methodName就是你和后台协定的规则 方法名

NSString *scheme=@"icocos:///";  前后台必须要一致

下面是js传参给oc  还是很麻烦的

 NSArray *array=[path componentsSeparatedByString:@"?"];

        NSLog(@"%@",array);

        NSString *methodName=array.firstObject;

        if (array.count == 2) {

          NSString *str = [array.lastObject stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

       NSDictionary *dict = [[NSString alloc] dictionaryWithJsonString:str];

posted @ 2016-08-11 14:55  JusDoit  阅读(332)  评论(0编辑  收藏  举报