I am trying to get some data from a local server, using a piece of code which worked in an Xcode playground file:
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
friend_ids = (jsonObj!.value(forKey: "friends") as? NSArray)!
}
}).resume()
return friend_ids
Having read some similar questions on this topic, I am aware that the URLSession runs asynchronously, such that the function is returning a nil value before any data is obtained from the server. I also think I understood that a completion handler can be used to ensure that the data is actually obtained before moving on, but unfortunately I wasn't really able to understand how to implement one. Might someone be able to show me how a completion handler would be used in this simple example, to ensure that the is obtained from the server before the variable is returned?
Thank you!