我在本地主机上有一个简单的 Playground 和一个简单的 TCP 服务器。我想要做的就是能够取消已经排队的 readData 操作的 URLSessionStreamTask。疯狂的是,这个 Playground 在 iOS 或 tvOS 上运行得很好,但在 macOS 上却不行。
在 iOS/tvOS 上,我得到以下输出:
Resuming...
Cancelling...
After cancel call
Victory! The session task was properly cancelled!
在 macOS (10.11) 上“胜利!”消息永远不会被打印。
这里是 Playground :
import Foundation
import PlaygroundSupport
let task = URLSession.shared.streamTask(withHostName: "localhost", port: 12345)
task.readData(ofMinLength: 1, maxLength: 1024, timeout: 0) { (data, atEOF, error) in
if let error = error as? NSError {
if error.code == NSURLErrorCancelled {
print("Victory! The session task was properly cancelled!")
}
}
}
print("Resuming...")
task.resume()
print("Cancelling...")
task.cancel()
print("After cancel call")
PlaygroundPage.current.needsIndefiniteExecution = true
我在这里遗漏了什么吗?我正在使用 XCode 8(测试版 4)。任何帮助深表感谢。谢谢。
最佳答案
我确定这现在已经很旧了,但在 10.12 下这似乎可以正常工作。
Resuming...
Cancelling...
After cancel call
Victory! The session task was properly cancelled!
关于swift - 取消 URLSessionStreamTask 永远不会使用 NSURLErrorCancelled 调用completionHandler(在 macOS 上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38842123/