无法将类型 'String' 的值转换为指定类型 'NWEndpoint.Host'

Cannot convert value of type 'String' to specified type 'NWEndpoint.Host'

通过 UDP 发送命令的 SwiftUI 代码


我想要的

我需要这样设置:

var hostUDP: NWEndpoint.Host = "192.168.0.205" //Line I want to fill with dispositive.ip
var portUDP: NWEndpoint.Port = 3489 //Line I want to fill with dispositive.port

到决定性结构中的值。我知道我不能在视图外执行此操作,但我也不能在视图内执行此操作。


错误

Cannot convert value of type 'String' to specified type 'NWEndpoint.Host'

var IP: NWEndpoint.Host = dispositive.ip


代码

这是我的代码:

import SwiftUI
import Foundation
import Network
var connection: NWConnection?
var hostUDP: NWEndpoint.Host = "192.168.0.205"
var portUDP: NWEndpoint.Port = 3489

struct CommunicationsView: View {
    
    var dispositive: Dispositive

    @State var confirm = false
    @State var command: String = ""
    
    var body: some View {
        
        VStack {
            HStack{
                VStack{
                    HStack{
                            Button(action: {
                                var IP: NWEndpoint.Host = dispositive.ip
                                self.connectToUDP(hostUDP, portUDP, message:"<ARRIBA1>")
                            }) {
                                Text("Y+")
                            }
                    }
                    .padding()
                    .background(
                        Capsule()
                            .stroke(Color.blue, lineWidth: 1.5)
                        )
                    
                    HStack{
                        Button(action: {
                            self.connectToUDP(hostUDP, portUDP, message:"<IZQUIERDA1>")
                        }) {
                            Text("X-")
                        }
                        .padding()
                        .background(
                            Capsule()
                                .stroke(Color.blue, lineWidth: 1.5)
                            )
                        Button(action: {
                            self.connectToUDP(hostUDP, portUDP, message:"<PARAR>")
                        }) {
                            Text("STOP")
                                .font(.subheadline)
                                .bold()
                        }
                        .padding()
                        .background(
                            Capsule()
                                .stroke(Color.blue, lineWidth: 1.5)
                            )
                        Button(action: {
                            self.connectToUDP(hostUDP, portUDP, message:"<DERECHA1>")
                        }) {
                            Text("X+")
                        }
                        .padding()
                        .background(
                            Capsule()
                                .stroke(Color.blue, lineWidth: 1.5)
                            )
                    }
                    HStack{
                        Button(action: {
                            self.connectToUDP(hostUDP, portUDP, message:"<ABAJO1>")
                        }) {
                            Text("Y-")
                        }
                    }
                    .padding()
                    .background(
                        Capsule()
                            .stroke(Color.blue, lineWidth: 1.5)
                        )
                }
                .padding()
                Divider()
                    .padding()
                    .frame(height: 200)
                VStack{
                    HStack{
                        Button(action: {
                            self.connectToUDP(hostUDP, portUDP, message:"<SUBIR>")
                        }) {
                            Text("Z+")
                        }
                        .padding()
                        .background(
                            Capsule()
                                .stroke(Color.blue, lineWidth: 1.5)
                            )
                    }
                    HStack{
                        Button(action: {
                            self.connectToUDP(hostUDP, portUDP, message:"<BAJAR>")
                        }) {
                            Text("Z-")
                        }
                        .padding()
                        .background(
                            Capsule()
                                .stroke(Color.blue, lineWidth: 1.5)
                            )
                    }
                }
                .padding()
            }
            
                
                
                VStack(alignment: .leading) {
                    Text("Terminal input")
                        .font(.callout)
                        .bold()
                    HStack{
                        TextField("Enter new command to send...", text: $command)
                            .textFieldStyle(RoundedBorderTextFieldStyle())
                        
                        Button(action: {
                            self.confirm = true
                        }) {
                            Text("Enviar")
                        }
                        .actionSheet(isPresented: $confirm){
                            ActionSheet(
                                title: Text("Send custom message"),
                                message: Text("Are you Sure?"),
                                buttons: [
                                    .cancel(Text("Cancel")),
                                    .destructive(Text("Yes"), action: {
                                        print("Sound the Alarm")
                                        self.connectToUDP(hostUDP, portUDP, message:command)
                                    })
                                ]
                            )
                        }
                    }
                }.padding()
            }
    }
    
    func connectToUDP(_ hostUDP: NWEndpoint.Host, _ portUDP: NWEndpoint.Port, message: String) {
        // Transmited message:
        let messageToUDP = message

        connection = NWConnection(host: hostUDP, port: portUDP, using: .udp)

        connection?.stateUpdateHandler = { (newState) in
            print("This is stateUpdateHandler:")
            switch (newState) {
                case .ready:
                    print("State: Ready\n")
                    self.sendUDP(messageToUDP)
                    self.receiveUDP()
                case .setup:
                    print("State: Setup\n")
                case .cancelled:
                    print("State: Cancelled\n")
                case .preparing:
                    print("State: Preparing\n")
                default:
                    print("ERROR! State not defined!\n")
            }
        }

        connection?.start(queue: .global())
    }
    
    func sendUDP(_ content: String) {
        let contentToSendUDP = content.data(using: String.Encoding.utf8)
        connection?.send(content: contentToSendUDP, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
            if (NWError == nil) {
                print("Data was sent to UDP")
            } else {
                print("ERROR! Error when data (Type: Data) sending. NWError: \n \(NWError!)")
            }
        })))
    }

    func receiveUDP() {
        connection?.receiveMessage { (data, context, isComplete, error) in
            if (isComplete) {
                print("Receive is complete")
                if (data != nil) {
                    let backToString = String(decoding: data!, as: UTF8.self)
                    print("Received message: \(backToString)")
                } else {
                    print("Data == nil")
                }
            }
        }
    }
    
}


struct CommunicationsView_Previews: PreviewProvider {
    static var previews: some View {
        CommunicationsView(dispositive: Dispositive(id: 1, name: "Nombre", description: "Descripción", color: .blue, banner: Image(""), ip: "192.168.0.84", port: 8888, control: 1, avatar: Image("user"), favorite: true)).previewLayout(.fixed(width: 400, height: 320))
    }
}

决定性的

决定性结构:

struct Dispositive {
    var id: Int
    var name: String
    var description: String
    var color: Color
    var banner: Image
    var ip: String
    var port: Int
    var control: Int
    var avatar: Image
    var favorite: Bool
}

尝试使用以下代码初始化 HostPort

主机-:

let hostUDP: NWEndpoint.Host = .init(dispositive.ip)

这是推荐的方法,您可以通过在 NWEndpoint enum 上执行 command + click 来检查同样的方法,然后查看 Host初始化程序。

端口-:

  let portUDP: NWEndpoint.Port = .init(integerLiteral: UInt16(dispositive.port))