1

I have a function in swift that read a file content as string and convert that into json object using jsonserialization. I want to pass that json object to wkwebview JavaScript function as object. So that I can access the data from JavaScript.

Iam using the evaluatescript method of swift

1 Answer 1

3

I have solved the issue by

Swift Code

func readFromFile(_ fileurl: String) {
    var myData:String = "";
    do {
        let url = NSURL(string: fileurl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
        myData = try String(contentsOf: url! as URL)
        let data = myData.data(using: String.Encoding.utf8, allowLossyConversion: false)!
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
            let serializedData = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
            let encodedData = serializedData.base64EncodedString(options:.endLineWithLineFeed)
            let js2:String = "LoadJson('\(encodedData)')"
            self.wkWebView?.evaluateJavaScript(js2, completionHandler: { (AnyObject, NSError) -> Void in
                NSLog("%s", #function)
                self.showMessage("Loaded")
            })
        } catch let error as NSError {
            print("Failed to load: \(error.localizedDescription)")
        }
    } catch{
        showMessage("Loading error.");
    }
}

Javascript code

function LoadJson (encodedData) {
   try {
      var decodedData = window.atob(encodedData);
      jsonObj = JSON.parse(decodedData);
   }
   catch (err) {
   }
}
Sign up to request clarification or add additional context in comments.

Comments

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.