1

I have opened an Output Stream from the sender iPhone and also implemented an Input (receiving ) Stream in the receiving iPhone. I am able to connect both the devices over the same Wi-Fi network using Multipeer Connectivity and send the data (I converted an audio file to NSData format to send it via Outputstream).But while receiving,only part of the NSData that I sent gets received.And every time I repeat running the code, varying amount of data gets received. Here is the Output Stream code:

     let outputStream: NSOutputStream = try! session.startStreamWithName(name, toPeer: session.connectedPeers[0])
            print("stream created")
            outputStream.delegate = self
            outputStream.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
            outputStream.open()
            print("Before filewritten")
            outputStream.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)
            print("filewritten")
            outputStream.close()

And my Input stream code is:

            var bytesRead = 0
    var buffer = [UInt8](count: 15000000, repeatedValue: 0)
    NSLog("%@", "didReceiveStream")
    stream.delegate = self
    stream.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
    stream.open()
    while (stream.hasBytesAvailable){
       bytesRead = stream.read(&buffer, maxLength: buffer.count)
        print("data fetched"+"\(bytesRead)")
    }

        stream.close()

Any help regarding the cause of this partial receipt of data and subsequent changes in code to formulate a solution will be extremely appreciated.

ANUVIND
  • 73
  • 4

1 Answers1

2

The documentation for NSOutputStream indicates that the return code of write(_:maxLength:) should be checked with:

let result = outputStream.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)

Return Value: The number of bytes actually written, or -1 if an error occurs. More information about the error can be obtained with streamError. If the receiver is a fixed-length stream and has reached its capacity, 0 is returned.

I recommend you to check this return code, and to fetch the data by slice.

xlasne
  • 96
  • 5