首页 > 解决方案 > 未为使用 getBoundStreams 创建的 InputStream 调用 StreamDelegate 方法

问题描述

我正在创建一对绑定的流并为我的输入流设置一个委托,如下所示:

class ViewController: UIViewController {

    private var inputStream: InputStream?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        inputStream = createStream()
        inputStream?.delegate = self
        // Open inputStream an try to read from it...
    }
    
    func createStream() -> InputStream {
        var output: OutputStream? = nil
        var input: InputStream? = nil
        Stream.getBoundStreams(withBufferSize: 1024, inputStream: &input, outputStream: &output)
        
        DispatchQueue.global().async {
            output!.open()
            for _ in 0..<3 {
                output!.write(data: "str".data(using: .utf8)!)
                sleep(1)
            }
            output!.close()
        }
        return input!
    }
}

extension ViewController: StreamDelegate {
    func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
        print(eventCode)
    }
}

extension OutputStream {
    @discardableResult
    func write(data: Data) -> Int {
        return data.withUnsafeBytes {
            write($0.bindMemory(to: UInt8.self).baseAddress!, maxLength: data.count)
        }
    }
}

Bt myStreamDelegate永远不会被调用。有没有办法来解决这个问题?

标签: iosswiftstream

解决方案


  • 你错过了一个open()电话InputStream
  • 两个流都必须附加到 runloop 以取得进展,例如stream?.schedule(in: RunLoop.current, forMode: RunLoop.Mode.default)

推荐阅读