I am using NWconnection to force some requests to go through cellular data. Everything works fine, except I keep calling connection.receive and don't know when the transfer is complete.
// Setting up the connection:
let tcpOptions = NWProtocolTCP.Options()
let parameters = NWParameters(tls: .init(), tcp: tcpOptions)
parameters.requiredInterfaceType = .cellular
port = port ?? NWEndpoint.Port(443)
// ...
NWConnection(to: .hostPort(host: NWEndpoint.Host(host),port: port), using: parameters)
// Receiving data once the connection is ready
func receive(withConnection connection: NWConnection, completion: @escaping dataCompletion) {
connection.receive(minimumIncompleteLength: 1, maximumLength: Int.max) { [self] data, contentContext, isComplete, error in
if let data = data {
receivedData.append(data)
print(contentContext)
if isComplete || error != nil || connection.state != .ready {
cancelConnection(connection)
} else {
processor?.receive(withConnection: connection, completion: completion)
}
} else {
cancelConnection(connection)
}
}
}
I am consuming regular HTTP endpoints. The data in receive comes in chunks but isComplete parameter never becomes true, so I don't know when to stop and send the complete receivedData back.
I've thought of adding a timeout, but it seems kind of hacky. Is there a better solution?