Hi Quinn, sorry for my late reply and this is my update.
I tried with the code below and received the same error in the question.
I am afraid I can't pass .tls to NWConnection for connection because the host address does not have https or wss at the beginning and the sec_protocol_options_set_verify_block callback wasn't triggered.
I tried putting https or wss at the beginning of the host but unfortunately, it couldn't connect.
class ViewModel {
var connection: NWConnection?
func connect() {
let connection = NWConnection(host: "XX.X.XXX.XX", port: 1515, using: createTLSParameters(allowInsecure: true, queue: .main))
self.connection = connection
connection.stateUpdateHandler = { newState in
print("newState \(newState)")
}
connection.start(queue: .main)
}
func createTLSParameters(allowInsecure: Bool, queue: DispatchQueue) -> NWParameters {
let tlsOptions = NWProtocolTLS.Options()
sec_protocol_options_set_verify_block(tlsOptions.securityProtocolOptions, { (sec_protocol_metadata, sec_trust, sec_protocol_verify_complete) in
let trust = sec_trust_copy_ref(sec_trust).takeRetainedValue()
var error: CFError?
if SecTrustEvaluateWithError(trust, &error) {
sec_protocol_verify_complete(true)
} else {
if allowInsecure == true {
sec_protocol_verify_complete(true)
} else {
sec_protocol_verify_complete(false)
}
}
}, queue)
return NWParameters(tls: tlsOptions)
}
}
let viewModel = ViewModel()
viewModel.connect()
I did some research and I think my issue might be similar to this question in this link.
Because that question was posted 4 years ago so do you have any updates on that issue and can we switch from TCP to TLS now?