10

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
  • 2
    Have you tried adding as? NSDictionary? Commented Jun 5, 2015 at 6:45
  • yes, it's also giving nil Commented Jun 5, 2015 at 6:50
  • Is it not possible to use the NSURL classes to fetch the JSON? Otherwise you are at the mercy of connection speeds and server response times. My only other thoughts are whether you can use a JSVirtualMachine, like I've done in this Playground where all JS is local. Commented Jun 5, 2015 at 7:22

3 Answers 3

4

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
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Thanks it worked. I was trying to fetch parsed object and it didn't work.
0

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.

5 Comments

there is only text data, so obviously less than 1MB, It's taking 1-2 sec in Safari > Develop > iOS simulator, as I mentioned.
Where you called this method ?
I called this method on one button's IBAction, I am pressing button after page completely loaded.
Sorry, but it is confidential.
then only last one suggestion , you may try to call this method within webviewdidfinish delegate

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.