Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting return value from JavaScript in UIWebView

I want to fetch JavaScript return value in my ViewController,

The problem is that, if there is small amount of data like String, I'm getting it.

But if there is large data like JSON object,It's showing nil.

When I call same JS function in Safari > Develop > iOS simulator, it's giving JSON object after 1-2 secs.

Here is my code:

var value = IBwebView.stringByEvaluatingJavaScriptFromString("get_small_string()")
println(value)   //Printing value

but this prints nil,

var value = IBwebView.stringByEvaluatingJavaScriptFromString("get_JSON()")
println(value)   //Printing nil

anyone knows how can I fetch big size JS return value in iOS object?

like image 271
Mohammad Zaid Pathan Avatar asked Jun 05 '15 06:06

Mohammad Zaid Pathan


2 Answers

This solve my problem,

var value = IBwebView.stringByEvaluatingJavaScriptFromString("get_JSON()")

var err:NSError?
var obj:AnyObject? = NSJSONSerialization.JSONObjectWithData(value!.dataUsingEncoding(NSUTF8StringEncoding)!, options:nil, error:&err)

if let items = obj as? NSDictionary {
var data1:String = items.objectForKey("data1") as? String
var data2:String = items.objectForKey("data2") as? String
var data3:String = items.objectForKey("data3") as? String
}
like image 136
Mohammad Zaid Pathan Avatar answered Nov 10 '22 17:11

Mohammad Zaid Pathan


As soon as you will return an object it will not work, what you can try instead is to return a stringified version of your object

JSON.stringify(yourObject);

And parse this string on the native side.

like image 41
oiledCode Avatar answered Nov 10 '22 16:11

oiledCode