我在swift中有一个函数,它将文件内容读取为字符串,并使用jsonserialization将其转换为json对象。我想将该json对象传递给wkwebview JavaScript函数作为对象。这样我就可以从JavaScript访问数据。
我使用swift
的evaluateatescript方法答案 0 :(得分:2)
我已经通过
解决了这个问题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代码
function LoadJson (encodedData) {
try {
var decodedData = window.atob(encodedData);
jsonObj = JSON.parse(decodedData);
}
catch (err) {
}
}