iOS_WKWebView_Interaction between native and JS_You can get the native return value immediately

  1. WKWebViewThe system comes with API
    reference: https://blog.csdn.net/baihuaxiu123/article/details/51286109
  2. Use a third-party framework WebViewJavascriptBridge, there is a detailed usage introduction in the
    link WebViewJavascriptBridge
  3. The above interaction methods are asynchronous, and the JSnative return value cannot be obtained immediately. Now introduce how to get the native return value
    3.1 immediately and follow the corresponding protocol
        _webView.UIDelegate = self;

3.2. Implement the content of the agreement

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
    NSError *err = nil;
    NSData *dataFromString = [prompt dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *payload = [NSJSONSerialization JSONObjectWithData:dataFromString options:NSJSONReadingMutableContainers error:&err];
    if (!err){
        NSString *type = [payload objectForKey:@"type"];
        if (type && [type isEqualToString:@"JSbridge"]){
            completionHandler([self getReturnValueWithPayload:payload]);
        }
    }
}
// 自定义方法
- (NSString *)getReturnValueWithPayload:(NSDictionary *)payload{
    NSString *returnValue = @"";
    NSString *functionName = [payload objectForKey:@"functionName"];
    NSDictionary *args = [payload objectForKey:@"arguments"]; // JS传入的值
    if ([functionName isEqualToString:@"getUserData"]) {
        NSDictionary *dictionary = @{@"userCode":@"1231231231" };
        returnValue = [self toJsonWithDictionary:dictionary];
    }
    return returnValue;
}
// 字典转化为JSON字符串
- (NSString *)toJsonWithDictionary:(NSDictionary *)dict{
    if (dict == nil || dict.allKeys.count == 0) {
        return @"";
    }else{
        NSError *parseError = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&parseError];
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
}

3.3, JScall native method

// 声明
function getNativeDataFunction(functionName,parm = {}){
    var payload = {"type": "JSbridge", "functionName": functionName, "arguments": parm};
    return prompt(JSON.stringify(payload));
}
// 调用 nativeData即接收的返回值<JSON字符串>
var  nativeData =  getNativeDataFunction("getUserData");

Guess you like

Origin blog.csdn.net/FlyingKuiKui/article/details/98619845