1

I have been trying to send image data from android and receive at iOS using Socket,But the problem is that I am not able to show Image from data which is received from stream.

Here is the complete code:-

Setting Up the network communication

var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault,
                                           ip as CFString,
                                           3003,
                                           &readStream,
                                           &writeStream)

        inputStream = readStream!.takeRetainedValue()
        outputStream = writeStream!.takeRetainedValue()
        inputStream.delegate = self
//        outputStream.delegate = self
        inputStream.schedule(in: .current, forMode: RunLoop.Mode.common)
        outputStream.schedule(in: .current, forMode: RunLoop.Mode.common)
        inputStream.open()
        outputStream.open()

Receive data through the delegates as shown below:-

extension ChatRoom: StreamDelegate {
    func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
        switch eventCode {
        case Stream.Event.hasBytesAvailable:
            print("new message received")
            readAvailableBytes(stream: aStream as! InputStream)
        case Stream.Event.endEncountered:
            print("end received")
            stopStreamSession()
        case Stream.Event.errorOccurred:
            print("error occurred")
        case Stream.Event.hasSpaceAvailable:
            print("has space available")
        case Stream.Event.openCompleted:
            print("Stream opened")
        default:
            print("some other event...")
            break
        }
    }
    private func readAvailableBytes(stream: InputStream) {
        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: maxReadLength)
        while stream.hasBytesAvailable {

            let numberOfBytesRead = inputStream.read(buffer, maxLength: maxReadLength)

            if numberOfBytesRead < 0 {
                if let _ = stream.streamError {
                    break
                }
            }

            NSLog("number of bytes read = %i", numberOfBytesRead)

            if numberOfBytesRead > 0 {
            dataOfImage.append(buffer, count: numberOfBytesRead)

            }
        }

    }

}

I have been trying to show image from data received using UIImage(data:dataOfImage), But it is showing nil , when I inspect the dataOfImage it consists of all the data received from stream.

Can anyone suggest a way to get the image out of UnsafeMutablePointer<UInt8> Data.

Also if there is any better approach for data transfer through sockets, Please do Suggest..

vinay
  • 351
  • 1
  • 5
  • 16

1 Answers1

0

Rather than allocate memory declare a buffer variable with the capacity of maxReadLength.

And stream(_:handle:) is called multiple times. You have to check the result of the read function

private var dataOfImage = Data()

private func readAvailableBytes(stream: InputStream) {
    var buffer = [UInt8](repeating: 0, count: maxReadLength)
    let bytesRead = inputStream.read(&buffer, maxLength: maxReadLength)
    switch bytesRead {
    case 0: // success, end of file
    case -1: // error
    default: // append data
       dataOfImage.append(contentsOf: buffer)
    }

    NSLog("number of bytes read = %i", bytesRead)
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • the problem here is the i am unable to convert data to image with `UIImage(data:dataOfImage)` it gives me nil . – vinay Jun 06 '19 at 08:46