iOS OC JS交互

点击网页的按钮: 利用block的方式

JSContext *context = [self.yaoWebView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
       WEAKSELF
    context[@"invite"] = ^() {
        
        NSLog(@"+++++++Begin Log+++++++");
        NSArray *args = [JSContext currentArguments];
        
        for (JSValue *jsVal in args) {
            NSLog(@"JSJS%@", jsVal);
          //  NSString *jsonStr = [NSString stringWithFormat:@"%@",jsVal];
        //   NSDictionary * dic = [weakSelf dictionaryWithJsonString:jsonStr];
           

JSValue *this = [JSContext currentThis];
        NSLog(@"this: %@",this);
        NSLog(@"-------End Log-------");
        
    };

invite,这个就是网页(后台)要的方法名.具体原理后续再补充.
OC给JS传值
            [ weakSelf.logicView.pickUpWebV stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"update(%@)",numStr]];

这个方法调用时机:应该在webview 请求完成后再调用 js 方法,这里才能用stringByEvaluatingJavaScriptFromString,因为

要等页面加载完,页面没加载完就相当于有些对象不一定创建成功,那么用js时候就容易找不到对象

下边无关,请无视


json转字典
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        
        return nil;
        
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                         
                                                        options:NSJSONReadingMutableContainers
                         
                                                          error:&err];
    
    if(err) {
        
        NSLog(@"json解析失败:%@",err);
        
        return nil;
        
    }
    
    return dic;
    
}

扩展知识:

http://blog.csdn.net/lwjok2007/article/details/47058101

http://blog.csdn.net/lwjok2007/article/details/47058795

你可能感兴趣的:(iOS OC JS交互)