1

In my project I have pass String to JavaScript using stringByEvaluatingJavaScript it have passed successfully. But if I have pass JSON String and Array or Dictionary means it doesn't pass the values I don't know how to pass these.

Here I have mention the code I have tried for pass the string to JavaScript,

let param:String = "HI"
let _ = self.webView.stringByEvaluatingJavaScript(from: "myNewFunction('\(param)')")

It Successfully return the value HI

Here I Mentioned the JavaScript Code,

<!DOCTYPE html>
<html>
    <p>Click the button to display an alert box.</p>
    <script>
        function myNewFunction(param) {
            alert(param);
        }
    </script>
<body>
    <button onclick="myNewFunction()">Try it</button>
</body>
</html>

How can I pass the values like Array and Dictionary and the JSON String?

3
  • Why you do not convert your dictionary to jsonstring using jsonserializer ? Then you can pass the json string to your javascript method. Commented Nov 9, 2018 at 12:50
  • How, Can you please say?@HuseinBehboodiRad Commented Nov 9, 2018 at 12:52
  • check my answer Commented Nov 9, 2018 at 12:59

3 Answers 3

1
let dict:[String:Any] = ["key1":10,"key2":false, "key3": "Some string goes in here"]
        let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: [.prettyPrinted])
        if let data = jsonData{
            let value = String(data: data, encoding: .utf8)
            print( value )
        }

Output: Optional("{\n \"key1\" : 10,\n \"key2\" : false,\n \"key3\" : \"Some string goes in here\"\n}")

Code in Playground enter image description here

Result in Playground enter image description here

Here what was missing was the dictionary type inference i.e dict:[String:Any]. Also when you use try use optional along with it as it may throw an exception like try?

Sign up to request clarification or add additional context in comments.

Comments

0

This might work.. I haven't tested it yet:

if let data = try? JSONSerialization.data(withJSONObject: arrayOrDictionaryHere, options: [.prettyPrinted]), let param = String(data: data, encoding: .utf8) {
    self.webView.stringByEvaluatingJavaScript(from: "myNewFunction('\(param)')")
}


//JS:

function myNewFunction(param) {
    alert(JSON.parse(param))
}

1 Comment

This code working only for String Value not for other things.
0

Use following code for converting dictionary to jsonstring:

 var dict : Dictionary = ["key1":"value1","key2":"value2"]
let data = try JSONSerialization.data(withJSONObject: dict, options: [.prettyPrinted])
let value = String(data: data, encoding: .utf8)

and then call your javascript method using the string in value

if you replace dict in second line with and instance of json array then you will get json string of the json array too. I every thing will work for that too.

7 Comments

This code working only for String Value not for other things.
As I told you can convert your dictionary and array to string and then pass them to your javascript and in your javascript then convert the to array or dictionary.
OK. so in witch part you have the problem? In getting the json string in value or on receiving it on the java script? Can you see the json string in the value or not?
I have Used the below code only bro, let data = try JSONSerialization.data(withJSONObject: tempComponentArray, options: [.prettyPrinted]) let value = String(data: data, encoding: .utf8) let encodedStr = self.webView.stringByEvaluatingJavaScript(from: "myNewFunction('(String(describing: value))')") print("encodedStr: ",encodedStr!)
when I print the value means that returns empty.. print("encodedStr: ",encodedStr!)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.