This code in your Connect
class creates a singleton instance
static let sharedInstance = Connect()
Then the View
creates another instance with this
let communication = Connect()
One cannot see what the other is doing. It is like creating having 2 cars, 2 houses, 2 people.
Remove communication
and replace with connect
. Observe and use the Singleton.
struct ConnectView: View {
@ObservedObject var connect = Connect.sharedInstance
var body: some View {
VStack {
Text("Incoming Message - (self.connect.theMessage)")
.padding(100)
.onAppear(){
// LISTENER
let port2U = NWEndpoint.Port.init(integerLiteral: 1984)
connect.listenUDP(port: port2U)
}
Button(action: {
let host = NWEndpoint.Host.init("localhost")
let port = NWEndpoint.Port.init("1984")
self.connect.connectToUDP(hostUDP: host, portUDP: port!)
self.connect.sendUDP("/cue/MyText/start")
}) {
Text("smoke")
}
}// END VSTACK
}// END OF BODY
}// END OF VIEW
It is good practice to make the initializer of a class private
if you will have a Singleton pattern.
Add this to your Connect
class to prevent this issue.
private init(){
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…