如何在Swift中将UnsafeMutablePointer <UInt8>转换为UIImage

时间:2019-06-04 13:01:24

标签: ios swift sockets uiimage inputstream

我一直在尝试使用Socket从android发送图像数据,并在iOS上使用Socket接收图像,但是问题是我无法从流接收的数据中显示图像。

这是完整的代码:-

设置网络通信

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()

通过委托接收数据,如下所示:-

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)

            }
        }

    }

}

我一直试图显示使用UIImage(data:dataOfImage)接收的数据中的图像,但是显示nil,当我检查dataOfImage时,它包含从流中接收的所有数据。

谁能建议一种从UnsafeMutablePointer<UInt8>数据中获取图像的方法。

如果有更好的方法通过套接字传输数据,请执行建议。

1 个答案:

答案 0 :(得分:0)

声明allocate 变量而不是buffer的容量为maxReadLength

stream(_:handle:)被多次调用。您必须检查read函数的结果

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)
}