StreamDelegate method not called for an InputStream created using getBoundStreams

Viewed 88

I'm creating a bound pair of streams and set a delegate for my input stream like this:

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 my StreamDelegate is never called. Is there a way to fix this?

1 Answers
  • You are missing an open() call on the InputStream
  • Both streams must be attached to a runloop to make forward progress, e.g. stream?.schedule(in: RunLoop.current, forMode: RunLoop.Mode.default)
Related