【发布时间】:2020-01-02 00:05:11
【问题描述】:
我正在创建一个应用程序,它从 Alpha Vantage 获取股票数据并显示它,作为 Swift 的第一次尝试(我通常使用 JS 开发)。
更准确地说,我有一个表格视图,每个单元格都有以下标签:
- “打开”价格标签
- “高”价格标签
- “低价”标签
- “关闭”价格标签
- “音量”标签
这是我用于单元格的自定义类。
import UIKit
class StockChoiceCell: UITableViewCell {
@IBOutlet weak var openPriceLabel: UILabel!
@IBOutlet weak var highPriceLabel: UILabel!
@IBOutlet weak var lowPriceLabel: UILabel!
@IBOutlet weak var closePriceLabel: UILabel!
@IBOutlet weak var volumeLabel: UILabel!
}
我有一个异步函数,它成功地从 Alpha Vantage 检索所需数据并返回 [DataPoint],其中 DataPoint 是一个包含开盘价、最高价、最低价和收盘价以及交易量的结构。我说成功,因为我在应用程序的另一个方面使用该功能没有问题。
该函数类似于:
func retrieveDataFromAPI (tic: String, completion: @escaping ([DataPoint])->()) {
// Fetch stuff
// Pack it under the DataPoint structure
// ...
completion(arrayOfDataPoints)
}
这就是问题所在。
由于函数的异步特性,我不知道如何让应用程序在运行前“等待”数据获取完成:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! StockChoiceCell
// ... Setting stuff, etc.
return cell
}
我在网上搜索,主要尝试以下两个帖子,因为我的尝试之一是将异步函数嵌套在另一个同步函数中:
- How to return a bool to the outside function when you have nested functions in Swift?
- Wait until an asynchronous api call is completed - Swift/IOS
如果这是 JS,我会立即使用 Promise。但 Swift 对我来说是新手,我仍在探索异步函数在该语言中是如何工作的。
谢谢!
【问题讨论】:
-
.reloadData()上的UITableView是否可以满足您的需求?当您获得请求中的所有数据时,只需调用它即可。
标签: ios swift uitableview asynchronous