gpt4 book ai didi

swift - 在序列 swit 3 中附加异步响应

转载 作者:行者123 更新时间:2023-11-28 06:18:38 26 4
gpt4 key购买 nike

我正在生成一个自动收报机,它使用 dataTask 从 api 检索数据并通过 succsss 返回到函数

获取响应的函数需要按顺序追加或连接它们,但我无法完成。

这是我尝试过的方法,但都失败了,因为在单个自动收报机成功调用返回之前执行了最后一行打印。

    func getTicker() {

var tickerText = ""

tickerText += dataRequestnew("https://api-path-here/1") { success in return "First-item: \(success)" }
tickerText += dataRequestnew("https://api-path-here/2") { success in return " | Second-item: \(success)" }

print(tickerText)

}

或者

    var tickerText = ""

func getTicker() {

dataRequestnew("https://api-path-here/1") { success in
self.tickerText += "First-item: \(success)"
print(self.tickerText)
}
dataRequestnew("https://api-path-here/2") { success in
self.tickerText += " | Second-item: \(success)"
print(self.tickerText)
}

print(self.tickerText)
}

在第二个例子中,单个行情打印成功,但最后一个不成功,它只返回默认值。

问题

我怎样才能让代码按顺序运行,或者至少确保在所有 tickerText 调用成功返回后最后一次打印有效。

谢谢。

最佳答案

作为一个选项,您可以在第一个响应中调用第二个请求。然后才打印结果。

var tickerText = ""

func getTicker() {

dataRequestnew("https://api-path-here/1") { success in
self.tickerText += "First-item: \(success)"
dataRequestnew("https://api-path-here/2") { success in
self.tickerText += " | Second-item: \(success)"
print(self.tickerText)
}
}
}

关于swift - 在序列 swit 3 中附加异步响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44358826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com