Swift - 如何等到变量达到某个值后再继续执行?

问题描述 投票:0回答:1

我正在开发一个使用 MQTT 协议进行通信的应用程序。我想在建立连接后订阅一个主题。这是我到目前为止所拥有的并且它有效,但我知道有更好的方法来实现它。

class nodeManager: ObservableObject {
    //other declarations
    var mqttManager: MQTTManager = MQTTManager.shared()
    
    init() {
        Task {
            await testAsyncMqttInit()
        }
    }
    
    func testAsyncMqttInit() async {
        mqttManager.initialitizeMQTT(host: "127.0.0.1", identifier: "CG_App")
        mqttManager.connect()

        while mqttManager.currentAppState.appConnectionState.isConnected == false {
        }

        mqttManager.subscribe(topic: "#")
    }
// other functions
}

mqttManager 使用 CocoaMQTT 框架。我正在尝试更有效地检查应用程序状态是否已连接,一旦连接,就执行订阅主题代码。

非常感谢任何帮助:)

swift async-await wait
1个回答
0
投票
func connect() async -> CocoaMQTTConnAck {
    await withCheckedContinuation { continuation in
        connect { connAck in
            continuation.resume(returning: connAck)
        }
    }
}

func connect(completion: @escaping (CocoaMQTTConnAck) -> Void) {
    let clientID = "FindMySync-" + String(ProcessInfo().processIdentifier)

    mqttClient = CocoaMQTT(clientID: clientID, host: mqttConfiguration.host, port: mqttConfiguration.port)

    if let client = mqttClient {
        client.username = mqttConfiguration.user
        client.password = mqttConfiguration.password
        client.enableSSL = mqttConfiguration.ssl
        client.didConnectAck = { client, connAck in
            completion(connAck)
            return
        }
        let _ = client.connect()
    }
}
    
let connAck = await connect()
© www.soinside.com 2019 - 2024. All rights reserved.