I need to call a JavaScript function from a local JavaScript file and then Call JS Function CalcualatePremiumWeb and get the returned value from JS printed in Swift. However, I'm encountering an error when trying to evaluate the JavaScript function and retrieve the result.
Swift
Still Failing, JS Function that i wanna call;
Error List:
Swift
Swift:
guard let jsPath = Bundle.main.path(forResource: "ValidationHealth", ofType: "js") else {
print("Failed to find the JavaScript file")
return
}
let encodings: [String.Encoding] = [.utf8, .utf16, .utf32, .windowsCP1252]
for encoding in encodings {
do {
let jsContent = try String(contentsOfFile: jsPath, encoding: encoding)
let userScript = WKUserScript(source: jsContent, injectionTime: .atDocumentStart, forMainFrameOnly: true)
let userContentController = WKUserContentController()
userContentController.addUserScript(userScript)
let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController
let webView = WKWebView(frame: .zero, configuration: configuration)
webView.loadHTMLString("", baseURL: nil)
let javascriptFunction = "CalcualatePremiumWeb(\(json), 'COMBO');"
webView.evaluateJavaScript(javascriptFunction) { (result, error) in
if let error = error {
print("Evaluation error: \(error)")
} else {
if let resultString = result as? String {
print("Evaluation result: \(resultString)")
} else {
print("Evaluation result is not a string: \(String(describing: result))")
}
}
}
return
} catch {
continue
}
}
print("Failed to read the contents of the JavaScript file")
Still Failing, JS Function that i wanna call;
JavaScript:
async function CalcualatePremiumWeb(inputs, type = "") {
var TotalParams = [];
var BaseParam = {};
if (type == "COMBO" && inputs.ComboInput != null && inputs.ComboInput != undefined)
{
for (var input of inputs.ComboInput) {
BaseParam = input.PolicyDetails;
BaseParam.push({ key: "@PR_ID", value: input.ProductId });
Object.keys(inputs.PolicyDetails).forEach(function (k) {
if (!BaseParam.hasOwnProperty(k)) BaseParam[k] = inputs.PolicyDetails[k];
});
TotalParams.push(BaseParam);
}
}
else
{
BaseParam = inputs.PolicyDetails;
TotalParams.push(BaseParam);
}
for (var param of TotalParams) {
var ProductId = parseInt(getParamsValue(param, "@PR_ID").Value);
await LoadFiles(ProductId, param);
var lstProdRider = eval("[PRODUCTRIDERMAP_" + ProductId + "][0]");
for (var i = 0; i < lstProdRider.length; i++)//see that I removed the $ preceeding the `for` keyword, it should not have been there
{
var RiderId = lstProdRider[i].RiderId;
//Load RiderFile
fileurl = "ProductRates/" + RiderId + "/" + RiderId + ".js";
if (isScriptAlreadyIncluded(fileurl) == false) {
await (loadJSfile(fileurl));
}
var JSList = LoadRateFiles(0, param, RiderId, 0);
for (var k = 0; k < JSList.length; k++) {
var fileurl = "ProductRates/" + RiderId + "/" + JSList[k];
if (isScriptAlreadyIncluded(fileurl) == false) {
await (loadJSfile(fileurl));
}
}
}
}
if (type == "COMBO") {
var resp = {
"Status": "",
"ErrorMessage": [],
"Card": []
};
var data = await MultiPremCalcAPI(inputs); //Combo
for (var card of data.Card) {
let newCard = {
"Status": "Fail",
"AddOns": [],
"Riders": [],
"OptionalPackage": [],
"ErrorMessage": [],
"SuggestionCode": "",
"SuggestionName": "",
"FinalPremiumTable": []
};
let transformedErrorMessage = transformKeysAndValues(card.ErrorMessage);
newCard.Status = card.Status || "";
newCard.AddOns = card.AddOns || [];
newCard.Riders = card.Riders || [];
newCard.OptionalPackage = card.OptionalPackage || [];
newCard.ErrorMessage = transformedErrorMessage || [];
newCard.SuggestionCode = card.SuggestionCode || "";
newCard.SuggestionName = card.SuggestionName || "";
newCard.FinalPremiumTable = card.FinalPremiumTable || [];
resp.Card.push(newCard);
}
if (resp.Card == null || resp.Card.Count == 0) {
err.push({ Key: "NoSuggestion", Value: "No suggestions found." });
resp.ErrorMessage = err;
} else {
if (
resp.Card.filter(
(bi) =>
bi.ErrorMessage != null && bi.ErrorMessage.length > 0
).length > 0
) {
resp.Status = "Fail";
} else {
resp.Status = "Success";
}
}
if (Device == "IOS") {
window.webkit.messageHandlers.netvest.postMessage(ReturnBIResponse(resp));
}
else if (Device == "ANDROID") {
return ReturnBIResponse(resp);
}
else {
var ChannelId = parseInt(getParamsValue(inputs.PolicyDetails, "@CHANNEL_ID").Value) || 0;
await SaveTransactionTracking("GetProductSuggestion", inputs, data, ChannelId);
return resp;
}
}
else {
var data = await ValidateInputAll(inputs); //Individual
let transformedErrorMessage = transformKeysAndValues(data.ErrorMessage);
data.ErrorMessage = transformedErrorMessage;
if (Device == "IOS") {
window.webkit.messageHandlers.netvest.postMessage(ReturnBIResponse(data));
}
else if (Device == "ANDROID") {
return ReturnBIResponse(data);
}
else {
var ChannelId = parseInt(getParamsValue(inputs.PolicyDetails, "@CHANNEL_ID").Value) || 0;
await SaveTransactionTracking("CalculateHealthPremium", inputs, data, ChannelId);
return data;
}
}
}
Error List:
Code:
Error calling JavaScript function: Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=ReferenceError: Can't find variable: Optional, WKJavaScriptExceptionColumnNumber=45, WKJavaScriptExceptionSourceURL=file:///Users/apple/Library/Developer/CoreSimulator/Devices/E354C94E-2468-4DC9-A762-66C6B42EAF96/data/Containers/Bundle/Application/AAEA1683-63C2-4E5B-ABA9-D1F593D99BA1/MCTest.app/XYZ/TestHealthFunction.html, NSLocalizedDescription=A JavaScript exception occurred}
JavaScript evaluation error: Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=ReferenceError: Can't find variable: CalcualatePremiumWeb, WKJavaScriptExceptionColumnNumber=21, WKJavaScriptExceptionSourceURL=undefined, NSLocalizedDescription=A JavaScript exception occurred}
Evaluation error: Error Domain=WKErrorDomain Code=5 "JavaScript execution returned a result of an unsupported type" UserInfo={NSLocalizedDescription=JavaScript execution returned a result of an unsupported type}