swift - 取消 URLSessionStreamTask 永远不会使用 NSURLErrorCancelled 调用completionHandler(在 macOS 上)

标签 swift macos nsurlsession osx-elcapitan

我在本地主机上有一个简单的 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/

相关文章:

iOS:如何在推送到 viewController 后继续显示 subview

ios - Swift 3.0 图像集

ios - swift 中出现此错误的原因是什么? : script error -54. 由于错误 -1700 无法获取错误文本

ios - 如何清理 nsurlsession downloadTask 生成的 tmp 文件?

nsurlsession - 清除 NSURLSession iOS 中的所有 cookie

swift - 使用嵌套函数

ios - 以 Xib 作为 Root View 的自定义 View

Xcode 4,断点在 Mac OS 命令行工具的单元测试中不起作用

swift - IOBluetoothDevice 注册不适用于 forConnectNotifications

ios - 来自太多请求的 NSURLSession 和地理编码器错误,解决方案是什么?