0

In my project I have pass String from swift to JavaScript and displaying in alert it works perfectly. But if I have pass array or dictionary means returns undefined values like

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

but I don't know how to fix the issue.

Here I have attached the screen shot for webview response.

I displayed the returned value in alert

Here I have share my code what I am tried,

override func viewDidLoad() {
    super.viewDidLoad()
    webView.delegate = self
    loadHTMLFromBundle()
}
func loadHTMLFromBundle(){
    let url = Bundle.main.url(forResource: "index", withExtension: "html")
    let urlRequest:URLRequest = URLRequest(url:url!)
    self.webView.loadRequest(urlRequest)
}

func getComponents() {
    guard let path = Bundle.main.path(forResource: "components", ofType: "txt") else { return }
    let url = URL(fileURLWithPath: path)

    let jsonData = try! Data(contentsOf: url)
    tempComponentArray = try! JSONSerialization.jsonObject(with: jsonData, options: []) as! NSArray
    print("jsonDict:\n \(tempComponentArray)")

    do {
        let jsonData = try JSONSerialization.data(withJSONObject: tempComponentArray, options: [])

        //Convert back to string. Usually only do this for debugging
        if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
            print(JSONString)
            let urlString:NSString = NSString(format: "myNewFunction(%@)", JSONString)
            print("urlString: ",urlString)
            self.templateFormStr = JSONString
            print(self.templateFormStr)
            let encodedStr = self.webView.stringByEvaluatingJavaScript(from: "myNewFunction('\(self.templateFormStr)')")   **-----------> Here I passed or evaluate the data to javascript**
            print("encodedStr: ",encodedStr!)
        }

    } catch {
        print(error.localizedDescription)
    }
}

@IBAction func loadJSBtnTapped(_ sender: Any) {
    getComponents()
}

Here I share the Array Values,

[
  {
    "placeholder": "Enter the comments",
    "input": true,
    "showWordCount": false,
    "label": "North",
    "showCharCount": false,
    "type": "textfield",
    "allowMultipleMasks": false,
    "key": "textField"
  },
  {
    "placeholder": "Enter the comments",
    "input": true,
    "showWordCount": false,
    "label": "South",
    "showCharCount": false,
    "type": "textfield",
    "allowMultipleMasks": false,
    "key": "south"
  },
  {
    "placeholder": "Enter the comments",
    "input": true,
    "showWordCount": false,
    "label": "East",
    "showCharCount": false,
    "type": "textfield",
    "allowMultipleMasks": false,
    "key": "east"
  },
  {
    "placeholder": "Enter the comments",
    "input": true,
    "showWordCount": false,
    "label": "West",
    "showCharCount": false,
    "type": "textfield",
    "allowMultipleMasks": false,
    "key": "west"
  },
  {
    "placeholder": "Enter the comments",
    "input": true,
    "showWordCount": false,
    "label": "Easements / Encroachments",
    "showCharCount": false,
    "type": "textfield",
    "allowMultipleMasks": false,
    "key": "easementsEncroachments"
  },
  {
    "placeholder": "Enter the comments",
    "input": true,
    "showWordCount": false,
    "label": "Soil ans Sub-Soil Conditions",
    "showCharCount": false,
    "type": "textfield",
    "allowMultipleMasks": false,
    "key": "soilAnsSubSoilConditions"
  },
  {
    "placeholder": "Enter the comments",
    "input": true,
    "showWordCount": false,
    "label": "Environmental Conditions",
    "showCharCount": false,
    "type": "textfield",
    "allowMultipleMasks": false,
    "key": "environmentalConditions"
  }
]

Here I have share my HTML code what I am tried,

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

When Display unparsed Json means alert shows empty, Here I have attached the screenshot.

enter image description here

13
  • What's expected behaviour? Because alert shows exactly what is expected: result of [{…}, {…}, {…}, {…}, {…}].toString(). Commented Nov 13, 2018 at 13:15
  • Expected behaviour was to display the correct values in alert. Commented Nov 13, 2018 at 13:17
  • I think you are okay, you receiving objects and you can use it. Try with console.log(arrayData); Commented Nov 13, 2018 at 13:18
  • @B.SaravanaKumar, that exactly what happens right now. Commented Nov 13, 2018 at 13:19
  • 2
    @B.SaravanaKumar, maybe you should keep JSON unparsed then, and call alert with that unparsed JSON string. Commented Nov 13, 2018 at 13:27

1 Answer 1

3

@user28434 is quite right. just unparse it. use var arrayData = param;

Why not use WKWebView,

'UIWebView' was deprecated in iOS 12.0: No longer supported; please adopt WKWebView.

here is what I got:

image

html code:

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

native code

 @IBOutlet weak var webView: UIWebView!


override func viewDidLoad() {
    super.viewDidLoad()
    webView.delegate = self
    loadHTMLFromBundle()
    }
    func loadHTMLFromBundle(){
        let url = Bundle.main.url(forResource: "index", withExtension: "html")
        let urlRequest:URLRequest = URLRequest(url:url!)
        self.webView.loadRequest(urlRequest)
    }

    func getComponents() {
        guard let path = Bundle.main.path(forResource: "components", ofType: "txt")
            else {



                return }
        let url = URL(fileURLWithPath: path)

        let jsonData = try! Data(contentsOf: url)
        let tempComponentArray = try! JSONSerialization.jsonObject(with: jsonData, options: []) as! NSArray
        print("jsonDict:\n \(tempComponentArray)")

        do {
            let jsonData = try JSONSerialization.data(withJSONObject: tempComponentArray, options: [])

            //Convert back to string. Usually only do this for debugging
            if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
                print(JSONString)
                let urlString:NSString = NSString(format: "myNewFunction(%@)", JSONString)
                print("urlString: ",urlString)
                let templateFormStr = JSONString
                print(templateFormStr)
                let encodedStr = self.webView.stringByEvaluatingJavaScript(from: "myNewFunction('\(templateFormStr)')")


                print("encodedStr: ",encodedStr!)
            }

        } catch {
            print(error.localizedDescription)
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

this github.com/BoxDengJZ/tmp_S_O works, the problem was from comments.txt file..

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.