I am communicating with JS using Webview. I transfer into parameter api the received data again. But when Swift get an array from JS, Swift don't recognize it properly.
Where to Send Data from JS
var jsonData = {
data,
type : "fromjs"
};
alert(jsonData)
webkit.messageHandlers.sendFromJS.postMessage(jsonData);
Data Viewed by Alerts
{
"type" = "fromjs",
"data" = {
"num": "one",
"arr_data" : [{ "title": "test1", "val" : "testval1" },
{ "title": "test2" , "val" : "testval2"}]
}
}
I check the data received by Swift.
@available(iOS 8.0, *)
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "sendFromJS" {
let getdata = message.body as! NSDictionary
print(getdata)
But Swift doesn't recognize the array properly.
{
type = "fromjs",
data = {
"num": "one",
"arr_data" : ({ "title": "test1", "val" : "testval1" },
{ "title": "test2" , "val" : "testval2"})
}
}
Swift recognizes square brackets as parentheses.
How can you solve this problem? I have to send the data that I received by putting it in the parameters as it is.
func apiCall(_ param: NSDictionary){
let parameters: [String: AnyObject] = param["data"] as! [String : AnyObject]
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers)
I've changed the type of data. But it's equally unrecognizable.
let getdata = message.body as! [String : Any]
print(getdata)
//log From Swift
[
type = "fromjs",
data = {
"num": "one",
"arr_data" : ({ "title": "test1", "val" : "testval1" },
{ "title": "test2" , "val" : "testval2"})
}
]
To create json data in js
var data = {
num: "one"
};
var data_arr = [];
data_arr.push({"title": "test1", "val" : "testval1"});
data_arr.push({"title": "test2" , "val" : "testval2"});
data.arr_data = data_arr;
var jsonData = {
data,
type : "fromjs"
};
alert(jsonData)
webkit.messageHandlers.sendFromJS.postMessage(jsonData);