WKWebView
The system comes withAPI
reference: https://blog.csdn.net/baihuaxiu123/article/details/51286109- Use a third-party framework
WebViewJavascriptBridge
, there is a detailed usage introduction in the
link WebViewJavascriptBridge - The above interaction methods are asynchronous, and the
JS
native 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, JS
call 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");