After watching the “What is JSON” video, from a few weeks ago, I started experimenting with the code. I took all the JSON related code that was in ViewController and placed it in a method -> getJSONFeed().
My initial problem was how to get the data passed from the getJSONFeed() function, more specifically from the closure within that function, back into ViewController. I was basically trying to create a JSON method that would do all the heavy lifting and then just pass the code back to wherever it had originally been called.
I made a post on the actual video page but it was suggested to post here instead.
Interestingly enough…I’ve gotten a little further along since the original post. I have now been able to get the data passed back into ViewController. I used an escaping (@escape) closure with the desired return type. It is now passing the data BACK to ViewController but the data is STILL “trapped” inside the method call. I can work with the returned data as long as I stay within the braces of the method call but once I “step” outside the braces of the method call…the data no longer has scope and is not visible.
So I still have my same question: How to return data from an asynchronous function, within a method, back to the caller??
I have a 2nd question: If I change the return type of the escaping closure to (Any) I can then return either the NSArray or the NewsFeed object back to the caller…and the data is visible (within scope). However…when I have the escaping closure return the newFeed variable, not the rawArray (NSArray) data and then when the break occurs:
- I can see all the variables on the left side of the debug panel and the newsFeed variable is properly populated with all the articles from the end-point.
- Because it was returned as a type:Any I can’t seem to access any of the variable data on the right side of the debug panel other than “po array”. If I try to get more specific, as in “po array.totalResults” I get the following message and I can’t figure out WHAT command to type to access members of the array object. (Of course this problem doesn’t occur when the escaping closure’s return type is set to NewsFeed).
:3:7: note: cast ‘Any’ to ‘AnyObject’ or use ‘as!’ to force downcast to a more specific type to access members
( as AnyObject)
Any help with either (or both) of the above questions would be greatly appreciated.
NOTE: I have attached an image of the ViewController.swift file to this posting. It’s a fairly small class file.