无法将“字符串”类型的值转换为指定类型“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

属于决定性结构中的价值观。我知道我不能在 View 之外做这件事,但我也不能在里面做。


错误

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,message:"<IZQUIERDA1>")
                        }) {
                            Text("X-")
                        }
                        .padding()
                        .background(
                            Capsule()
                                .stroke(Color.blue,linewidth: 1.5)
                            )
                        Button(action: {
                            self.connectToUDP(hostUDP,message:"<ParaR>")
                        }) {
                            Text("STOP")
                                .font(.subheadline)
                                .bold()
                        }
                        .padding()
                        .background(
                            Capsule()
                                .stroke(Color.blue,message:"<DERECHA1>")
                        }) {
                            Text("X+")
                        }
                        .padding()
                        .background(
                            Capsule()
                                .stroke(Color.blue,linewidth: 1.5)
                            )
                    }
                    HStack{
                        Button(action: {
                            self.connectToUDP(hostUDP,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,message:"<SUBIR>")
                        }) {
                            Text("Z+")
                        }
                        .padding()
                        .background(
                            Capsule()
                                .stroke(Color.blue,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,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)

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

端口-:

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