简体   繁体   中英

iOS Swift: When I pass data like array or dictionary to Javascript means it returns Undefined value?

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.

我在警报中显示了返回的值

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.

在此处输入图片说明

@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:

图片

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)
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM