许多Cocoa和CocoaTouch方法都有完成回调,实现为Objective-C中的块和Swift中的闭包.但是,在Playground中尝试这些时,永远不会调用完成.例如:
// Playground - noun: a place where people can play
import Cocoa
import XCPlayground
let url = NSURL(string: "http://stackoverflow.com")
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.currentQueue() {
response, maybeData, error in
// This block never gets called?
if let data = maybeData {
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
println(contents)
} else {
println(error.localizedDescription)
}
}
Run Code Online (Sandbox Code Playgroud)
我可以在我的Playground时间轴中看到控制台输出,但是println我的完成块永远不会被调用...
我有一个 UDP 方法,它使用以下代码使用 DispatchQueue 等待回复:
DispatchQueue.global(qos: .userInitiated).async {
let server:UDPServer=UDPServer(address:"0.0.0.0", port:5005)
let (data,_,_) = server.recv(1024)
DispatchQueue.main.async {
...
}
}
Run Code Online (Sandbox Code Playgroud)
这非常有效,并启动了一个等待我的数据进来的过程。如果我们从未收到回复,让我夜不能寐的是会发生什么?server.recv 永远不会返回,所以我看不到这个过程将如何结束?有没有办法给它预定的运行时间?