func getTCPConnection(host: String, port: String, enableTLS: Bool) async throws -> NWTCPConnection? {
let endpoint = NWHostEndpoint(hostname: host, port: port)
// let enableTLS = true
let connection = createTCPConnectionThroughTunnel(to: endpoint, enableTLS: enableTLS, tlsParameters: nil, delegate: self)
var count = 0
while connection.state != .connected {
count += 1
try await Task.sleep(nanoseconds: 0_500_000_000)
if connection.state == .connected {
return connection
}
if connection.state == .disconnected {
self.flushLog("Connection state => disconnected. throw error")
throw StateMonitoringError.connectionDisconnected
}
if count > 30 {
self.flushLog("Connection time out")
if let error = connection.error {
self.flushLog("\(error)")
}
return nil
}
}
return nil
}
Previously, this function worked perfectly. However, when OnDemand Rules are set to true and the device is left idle for a long time (such as in Low Power Mode or with no activity), executing this function during the automatic reconnection process results in a connection timeout, because the connection takes too long to be established.
Topic:
App & System Services
SubTopic:
Networking
Tags: