简体   繁体   中英

Audio file is partially received in target iPhone from sender using Multipeer Connectivity(Swift 2)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM