I am trying to write a macOS application that connects to a radio scanner on a network connection via a UDP socket. The app sends commands to the scanner for remote control. I can get the app to work fine when I hard code the NWConnection initiation but when I put a variable that represents the port or host I get an Xcode error.
I want the user to be able to input their specific Host and Port address therefore I set up textFields for the user to input these values. Then I wanted to retrieve the values and enter them into the Host and Port NWConnection fields when initializing the connection.
Here is a code snippet:
func makeConnection(){
var myHost = "192.168.7.239"
var myPort = 50536 as UInt16
myConnection = NWConnection(host: myHost, port: myPort, using: .udp)
myConnection?.stateUpdateHandler = { (newState) in
switch (newState) {
case .ready:
print("ready")
self.send()
self.receive()
case .setup:
print("setup")
case .cancelled:
print("cancelled")
case .preparing:
print("preparing")
default:
print("waiting or failed")
}
}
In this case, if I replace myHost with "192.168.7.239" and I replace myPort with 50536 then Xcode is happy and everything works. However as soon as I put a variable in the host and port fields I get this complaint from Xcode.
"Type of expression is ambiguous without more context" and the build fails.
Why is this happening and how can I make an NWConnection without hard coding a Host or Port? what good is it is you can’t get the port and host from the user and use those values to make the connection.
Any help would be greatly appreciated.
2
Answers
When calling
NWConnection.init(host:port:using:)
, the parameterhost
needs to be of typeNWEndpoint.Host
,port
needs to beNWEndpoint.Port
.Please try this:
When you want to use the texts in textFields, you need to covert the texts into
NWEndpoint.Host
andNWEndpoint.Port
.XCode 14.0.1/Swift 5.7
I think it could be useful to complement OOPer’s answer a little bit.
Here, directly affecting a
String
value is OK.I think it’s expected since Apple’s documentation specificies
But if you use an intermediate variable to store the host IP address (for example if you get it through a user input in a
TextField
), be careful :is OK too. Expected since initializer expects a
String
.But:
returns a "Cannot convert value of type ‘String’ to specified type ‘NWEndpoint.Host’" error.
Seems confusing since it looks to be the same at first example, but with an intermediate variable.