Wait for a network call to complete before returning a value
<p>I'm trying to get and return some (json) data from a network call, and I'm wondering if there is a better way to wait for the network data other than just and empty loop.</p>

<p>Here's my code:</p>

<pre><code>func sendAPIRequest(endpoint:String) -&gt; JSON?
{
    var json = JSON("")
    let request = NSMutableURLRequest(URL: NSURL(string: "https://host.com/".stringByAppendingString(endpoint))!)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil &amp;&amp; data != nil else {                                                          // check for fundamental networking error
            print("error=\(error)")
            return
        }
        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
        }
        json = JSON(data: data!)
    }
    task.resume()
    while (json == "") {
        // Wait
    }
    return json
}
</code></pre>

<p>I remember trying something similar in Objective-C which resulted in an infinite loop at run time.</p>