【发布时间】:2020-03-25 13:24:08
【问题描述】:
我有一个小型测试 Swift 应用程序 (SwiftUI iOS/OSX),我正在尝试从中发送一个基本的 UDP 数据包。
在模拟器中运行并作为 OSX 应用程序时,它运行良好,但在物理 iOS 设备上运行时,NWConnection 会挂在 .prepaing 处,并且永远不会进一步。
我设置了 com.apple.security.network.server 和 com.apple.network.client 权利。
这是整个 SceneDelegate swift 文件,希望有人能看到我在这里做错了什么?
谢谢!
import SwiftUI
import Foundation
import Network
var connection: NWConnection?
var hostUDP: NWEndpoint.Host = "239.1.2.4"
var portUDP: NWEndpoint.Port = 40001
struct ContentView: View {
@State var confirm = false
var body: some View {
VStack {
Button(action: {
self.confirm = true
}) {
Text("Alarm")
}.actionSheet(isPresented: $confirm){
ActionSheet(
title: Text("Sound the Alarm"),
message: Text("Are you Sure?"),
buttons: [
.cancel(Text("Cancel")),
.destructive(Text("Yes"), action: {
print("Sound the Alarm")
self.connectToUDP(hostUDP, portUDP)
})
]
)
}
}
}
func connectToUDP(_ hostUDP: NWEndpoint.Host, _ portUDP: NWEndpoint.Port) {
// Transmited message:
let messageToUDP = "ALARM"
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")
}
}
}
}
}
【问题讨论】:
标签: ios swift xcode afnetworking