I am trying to send a series of numbers using a stream through Multipeer Connectivity. But the callback function of StreamDelegate is only called twice.
func startAngleDataStream(){
print("Starting stream")
guard iPadPeerID != nil else { return }
do{
if self.outputStream != nil{
self.outputStream!.close()
}
self.outputStream = try peerSession.startStream(withName: "myStream", toPeer: iPadPeerID!)
} catch {
print("Error starting stream")
return
}
guard self.outputStream != nil else { return }
self.outputStream!.delegate = self
self.outputStream!.schedule(in: .current, forMode: .default)
self.outputStream!.open()
}
The function above is called when the connection to the receiver is established.
func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
if state == .connected {
self.startAngleDataStream()
}
}
This is the stream function.
func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
guard shouldWriteOrientation else { return }
switch eventCode {
case .hasSpaceAvailable:
guard let outputStream = aStream as? OutputStream else { return }
var data = Data()
data.append(Data(bytes: &calculatedOrientation.x, count: MemoryLayout<Double>.size))
data.append(Data(bytes: &calculatedOrientation.y, count: MemoryLayout<Double>.size))
let _ = data.withUnsafeBytes {
outputStream.write(($0.baseAddress?.assumingMemoryBound(to: Double.self))!, maxLength: data.count)
}
shouldWriteOrientation = false
default:
break
}
}
I have checked the status of the stream, it’s open when the delegate stopped responding. There are no errors in the stream. I have also tried changing the scheduled thread to .main and mode to .common. The only two times the stream function is called, the receiver received the data correctly.