0

I’ve been trying to send image over TCP using Kitura BlueSocket.

Every time I try to decode image from Data object I get

Warning! [0x7fb6f205e400] Decoding incomplete with error code -1. This is expected if the image has not been fully downloaded.

And indeed the image is usually half-loaded. This is the code I use for downloading Data object:

func readData() -> Data {
        var receivedData = Data.init()

        do {
            try mySocket?.read(into: &receivedData)
        }
        catch {
            print("Error receiving data")
        }
        return receivedData
}

and this is how I decode image:

func decodeImage(from: Data){
    imageRead.image = UIImage(data: from)
}

and this code is used in the View Controller like so:

let imageData = networkManager.readData()
decodeImage(from: imageData)

I do not know why the image doesn't download fully.

Veiserath
  • 1
  • 1

1 Answers1

0

You're working with a low-level socket. TCP just knows about packets; it doesn't know anything about "images" or "records" or anything else. It just deals with packets. Depending on various factors, you may see packets as small as a few hundred bytes to as large as a few kB.

.read(into:) returns you whatever packets have arrived so far. It doesn't know where the boundaries of your image are. That's up to you to determine. You need to loop until all the data you want to process has arrived (what that means completely depends on the protocol you've designed). You can't run this on the main queue; it'll block your UI. It needs to run on a background queue.

A very common socket-level protocol is to send the length first, and then send the data. That way the reader knows how much data to expect, and will know when the transfer is done. If the sender doesn't know the size when it starts transmitting, then you would typically use an "end-of-transfer" token of some sort, or use a protocol that chunks the data into blocks, and then has some marker to note "this is the last block." But in any case, you'll need to choose or design a protocol you want to use here. (Or use an existing system like HTTP rather than a low-level socket.)

Rob Napier
  • 286,113
  • 34
  • 456
  • 610