【问题标题】:Cannot convert value of type 'String' to specified type 'NWEndpoint.Host'无法将“String”类型的值转换为指定类型“NWEndpoint.Host”
【发布时间】:2021-08-27 15:15:18
【问题描述】:

通过 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
}

【问题讨论】:

  • 试试 NWEndpoint.Host.StringLiteralType
  • @TusharSharma 它可以设置变量,但 NWConnection 抛出:无法将类型“NWEndpoint.Host.StringLiteralType”(又名“String”)的值转换为预期的参数类型“NWEndpoint.Host”。有办法“投射”它吗?
  • 尝试-> var IP: NWEndpoint.Host = .name(dispositive.ip, nil)。基本上如果你command + click 再去NWEndpoint 枚举,你就会明白很多。
  • 另一种推荐的创建主机方式-:var IP: NWEndpoint.Host = NWEndpoint.Host(dispositive.ip)。我再次检查Network 框架并提出建议。但是,建议将其作为创建 Host 的推荐方式。
  • @TusharSharma 谢谢!两者都工作!我试图对 PORT 做同样的事情,但我做不到。

标签: ios swift udp swiftui-environment network-framework


【解决方案1】:

尝试下面的代码来初始化HostPort

主机-:

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

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

端口-:

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

【讨论】:

  • integerLiteral 期望 UInt16 OP 对象属性声明为 Int 正确的解决方案是 let portUDP: NWEndpoint.Port = .init(integerLiteral: UInt16(dispositive.port))。顺便说一句,Swift 是一种类型推断语言let hostUDP: NWEndpoint.Host = .init(dispositive.ip)
  • 感谢您的纠正。我不知道它是类型安全/推断的,只是错过了以这种方式编写的流程:)
猜你喜欢
  • 2017-06-29
  • 1970-01-01
  • 2018-11-24
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
  • 2016-01-14
  • 1970-01-01
  • 2017-11-17
相关资源
最近更新 更多