Getting return value from JavaScript in UIWebView

3.2k Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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
}
1
On

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.

5
On

If your java script method "get_JSON()" return more than 10 MB data then its not allowed by stringByEvaluatingJavaScriptFromString method.

Or If it take more than 10 sec to process output ,in that case you will be get nil value as output.