首页 > 解决方案 > NWConnection 脚本适用于 iPhone 但不适用于 Apple Watch

问题描述

此脚本应通过 UDP 将 1234 发送到192.168.0.169, 端口4000。它适用于 iPhone SE 2,但不适用于 Apple Watch SE (watchOS 7.2)。

import WatchKit
import Network

class InterfaceController: WKInterfaceController {
    var connection: NWConnection?
    
    func sendUDP(_ content: Data) {
        guard let connection = self.connection else {
            return
        }
        connection.send(content: content, completion: NWConnection.SendCompletion.contentProcessed(({ (error) in if false {}})))
    }
    
    func DoubleToData(value: Double) -> Data {
        return withUnsafeBytes(of: value) { Data($0) }
    }
    
    override func awake(withContext context: Any?) {
        // Configure interface objects here.
    }
    
    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        self.connection = NWConnection(host: "192.168.0.169", port: 4000, using: .udp)
        self.connection?.start(queue: .global())
        let dataToSend = self.DoubleToData(value: 1234)
        self.sendUDP(dataToSend)
        
        self.connection?.cancel()
        self.connection = nil
    }
    
    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
    }
}

安慰:

2021-01-10 18:46:10.855218+0100 SensorStream WatchKit Extension[458:111723] [default] lookupMainFuncAddressInMachHeader:71: Invalid Swift entry point data
2021-01-10 18:46:10.855629+0100 SensorStream WatchKit Extension[458:111723] [default] lookupMainFuncAddressInMachHeader:77: Swift entry point addres could not be determined.
2021-01-10 18:46:21.751945+0100 SensorStream WatchKit Extension[458:111901] [connection] nw_socket_initialize_socket [C1.1:3] Data mode 0 unrecognized
2021-01-10 18:46:21.752084+0100 SensorStream WatchKit Extension[458:111901] [connection] nw_socket_add_input_handler [C1.1:3] Failed to initialize socket
2021-01-10 18:46:21.752262+0100 SensorStream WatchKit Extension[458:111901] [connection] nw_endpoint_flow_attach_protocols [C1.1 fd74:6572:6d6e:7573:d:efd1:e30:65fb.62742 in_progress socket-flow (satisfied (Path is satisfied), interface: ipsec2, scoped, ipv4)] Failed to attach socket protocol

标签: swiftudpwatchkitwatchos

解决方案


推荐阅读