session.dataTaskWithURL从未调用completionHandler

Rom*_*aun 6 nsurl nsurlsession swift

我有以下代码:

let urlPath:String = apiURL + apiVersion + url + "?api_key=" + apiKey
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
println(url!)
let task = session.dataTaskWithURL(url!, completionHandler: {(data, reponse, error) in
    println("Task completed")
    // rest of the function...
})
Run Code Online (Sandbox Code Playgroud)

永远不会调用completionHandler函数.我尝试在浏览器中调用URL,它运行正常.我试过另一个URL,它仍然无法正常工作.我检查过我的ios模拟器可以连接到互联网,确实如此.

我不知道为什么函数没有被调用,因为我没有任何错误,所以很难调试.

Mic*_*lum 26

任务永远不会完成,因为它永远不会开始.您必须使用其resume()方法手动启动数据任务.

let urlPath = apiURL + apiVersion + url + "?api_key=" + apiKey
let url = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()

let task = session.dataTaskWithURL(url) { data, response, error in
    print("Task completed")
    // rest of the function...
}

task.resume()
Run Code Online (Sandbox Code Playgroud)