我有一个异步函数,必须在计时器内的每个给定时间调用它。 为了避免 Xcode 错误,
func firetimer() {
let newtimer = Timer(timeInterval: 1.0, repeats: true) { newtimer in
self.myAsyncFunction() // 'async' call in a function that does not support concurrency
}
RunLoop.current.add(newtimer, forMode: .common)
}
我尝试将其放入任务中,但这在运行时出现“Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)”错误。
func firetimer() {
let newtimer = Timer(timeInterval: 1.0, repeats: true) { newtimer in
Task{
await self.myAsyncFunction() // not working
}
}
RunLoop.current.add(newtimer, forMode: .common)
}
事实上我不需要任何等待,下一次出现的函数可以在后者仍在工作时调用。 有什么提示可以做什么吗? 谢谢!
尝试创建一个支持功能:
myAsyncFunction
:func mySyncFunction() {
// Call the asynchronous function
Task {
await self.myAsyncFunction()
}
}
fireTimer
func fireTimer() {
let newTimer = Timer(timeInterval: 1.0, repeats: true) { newTimer in
self.mySyncFunction() // Synchronous
}
RunLoop.current.add(newTimer, forMode: .common)
}
}
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()