闭包代码不会在函数中执行

Clousure code won't execute wrapped in a function

我有一个闭包,将 http 调用包装在一个函数中,该函数通过单击按钮调用。但是当我调试时我可以看到闭包中的代码永远不会执行,程序在到达闭包时完全跳出函数。

func getTheForeCast(city: String) {
    println("Function  getForecast city passed = : \(city)")

    var webAddress: String = "http://www.weather-forecast.com/locations/\(city)/forecasts/latest"

    println("Web address url : \(webAddress)")

    let url = NSURL(string: webAddress)
    println(url!)

// PROGRAM EXITS FUNCTION HERE

    let openbrowserSession = NSURLSession.sharedSession().dataTaskWithURL(url!) {
        (data, response, error) in   
        // in the following code, session returns data, error, and response
        println("In closure")

        if error == nil {
            // no errors, convert html to readable data
            var urlConverted = NSString(data: data, encoding: NSUTF8StringEncoding)

            println(urlConverted)

            // run this asynchronously using a grand central dispatch 
            dispatch_async(dispatch_get_main_queue()) { self.webview_displayWeather.loadHTMLString(urlConverted, baseURL: nil) } // dispatch

        } else if error != nil {
            println("Error loading page")
            println(error.description)    
        }           
    } // closure
} // func

感谢任何意见。

您使用了错误的签名。使用

func dataTaskWithURL(_ url: NSURL,
   completionHandler completionHandler: ((NSData!,
                              NSURLResponse!,
                              NSError!) -> Void)?) -> NSURLSessionDataTask

NSURLSession创建的任务最初处于"suspended"状态。 创建任务后必须调用resume():

let openbrowserSession = NSURLSession.sharedSession().dataTaskWithURL(url!) {
    (data, response, error) in

    // ...

}
openbrowserSession.resume()

否则什么也不会发生。