0

i have a Swift code for retrieving and parsing JSON data from the web. everything seems to work fine except one problem i am facing right now. I tried to solve it for some time, have check all sources online.

I have created global dictionary "dicOfNeighbours" that would like to return as a result of parse to other class by calling "func startConnection".

dicOfNeighbours stores parsed data till it goes out of the closing bracket of the: "let task = session.dataTaskWithRequest(urlRequest) { ... }" After it stores just nil. And returned result is nil as well.

I have tried to pass "dicOfNeighbours" variable by reference using inout and it is still returns nil result.

there might some solution that i missed. I would appreciate any help and suggestions.

Thanks!

    var dicOfNeighbours = Dictionary<String, [Int]>()

        func startConnection() -> Dictionary<String, [Int]>{
                let requestURL: NSURL = NSURL(string: "http://www....data.json")!
                let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
                let session = NSURLSession.sharedSession()
                let task = session.dataTaskWithRequest(urlRequest) {
                    (data, response, error) -> Void in

                    let httpResponse = response as! NSHTTPURLResponse
                    let statusCode = httpResponse.statusCode

                    if (statusCode == 200) {

                        do{

                            let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

                            if let neighbours = json["neighbours"] as? [String: Array<Int>] {
                                    var i = 0
                                    for (index, value) in neighbours {
                                        self.dicOfNeighbours[index] = value

                                }

                            }

                        }catch {
                            print("Error with Json: \(error)")

                        }               
                    }
                }
                task.resume()
return self.dicOfNeighbours
            }
1
  • 1
    Use a closure, not a "return". dataTaskWithRequest: is async. Commented Jan 28, 2016 at 11:14

1 Answer 1

3

You are using return instead of using a callback. You are doing your parsing when the network connection is done; asynchronously.

To synchronize it, you'd need to use semaphores, but that is highly discouraged on the main thread.

Instead, do the appropriate things with the result when your completion block is executed. Think of the data task as 'do stuff, come back to me when you're done'.

Sign up to request clarification or add additional context in comments.

2 Comments

Do you think I can call "func startConnection()" like "do .... while (dicOfNeighbours == nil) ?? wait till it return me the result. I am a bit confused
I suppose you are to do stuff with the result - then encapsulate that in a function and call it from the completion block.

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.