I'm new to Swift and I'm trying to get the result from this function. I don't know how to access variables that are inside the closure that is passed to the sendAsynchronousRequest function from outside the closure. I have read the chapter on closures in the Apple Swift guide and I didn't find an answer and I didn't find one on StackOverflow that helped. I can't assign the value of the 'json' variable to the 'dict' variable and have that stick outside of the closure.
var dict: NSDictionary!
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response, data, error) in
var jsonError: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? NSDictionary
dict = json
print(dict) // prints the data
})
print(dict) // prints nil
The closure is then completed asynchronously so the main thread doesn't wait for it, so
is called before the closure has actually finished. If you want to complete another function using dict then you will need to call that function from within the closure, you can move it into the main thread if you like though, you would do this if you are going to be affecting UI.
You are calling an asynchronous function and printing
act
without waiting for it to finish. In other words, whenprint(dict)
is called, the function hasn't complete execution(hencedict
isnil
)Try something like
and put your JSON logic inside a
doSomethingWithJSON
function:This ensures that your logic is execute only after the URL request completes.