上一篇在 TwMarketTradingInfoManager 完成了拿取大盤成交量的 API,接下來,在原來的大盤 K 線頁的 Model,加上拿取大盤成交量功能的 API。命名為 func requestTwVolumeInfo()
。
var twExStockDataSet = [StockKLine]()
var twExVolumeDataSet = [TwMarketTradingInfo]() //
// MARK: - 給外部呼叫的 func
/// 會取這個月和前一個月台股加權指的 KLine data,單一個月,有可能 k 棒數量太少
func requestTwExKLineAndVolumeInfo() {
requestTwExKLineInfo()
requestTwVolumeInfo()
}
// MARK: - 拿大盤量
private func requestTwVolumeInfo() {
requestTwThisMonthVolumeInfo()
requestTwLastMonthVolumeInfo()
}
private func requestTwThisMonthVolumeInfo() {
let date = dateUtility.getStartOfMonth()
volumeManager.requestTwMarketDailyTradingInfo(date: date) { [weak self] volumeList, error in
self?.update(volumeList: volumeList)
self?.delegate?.didRecieveVolume(volumeDataSet: volumeList, error: error)
}
}
private func requestTwLastMonthVolumeInfo() {
let date = dateUtility.getLastMonthStartDate()
volumeManager.requestTwMarketDailyTradingInfo(date: date) { [weak self] volumeList, error in
self?.update(volumeList: volumeList)
self?.delegate?.didRecieveVolume(volumeDataSet: volumeList, error: error)
}
}
private func requestTwBefore2MonthVolumeInfo() {
let date = dateUtility.getMonthStartDate(date: Date(), add: -2)
volumeManager.requestTwMarketDailyTradingInfo(date: date) { [weak self] volumeList, error in
self?.update(volumeList: volumeList)
self?.delegate?.didRecieveVolume(volumeDataSet: volumeList, error: error)
}
}
private func update(volumeList: [TwMarketTradingInfo]) {
let updatedData = Set(self.twExVolumeDataSet + volumeList)
self.twExVolumeDataSet = Array(updatedData).sorted { $0.date.timeIntervalSince1970 < $1.date.timeIntervalSince1970 }
}
完成後,加上 delegate func 告訴 VC 有值的變化
protocol TwStockMarketKLineModelDelegate: AnyObject {
func didRecieveTaiEx(kLineDataSet: [StockKLine], error: Error?)
func didRecieveVolume(volumeDataSet: [TwMarketTradingInfo], error: Error?)
}
TwStockMarketKLineViewController 要補上新加的 delegate func
extension TwStockMarketKLineViewController: TwStockMarketKLineModelDelegate {
func didRecieveVolume(volumeDataSet: [TwMarketTradingInfo], error: Error?) {
print(model.twExVolumeDataSet)
}
func didRecieveTaiEx(kLineDataSet: [StockKLine], error: Error?) {
print(model.twExStockDataSet)
}
}
KLineViewController 也要加上 volumnDataSet 讓外部傳入。
var volumnDataSet = [TwMarketTradingInfo]()
然後在把 KLineVC 推進來的時候,要一起把加權指數的值傳下去。
@IBAction func pushKLineButtonDidTap(_ sender: Any) {
let storyboard = UIStoryboard(name: "KLine", bundle: nil)
if let vc = storyboard.instantiateViewController(withIdentifier: "KLineViewController") as? KLineViewController {
vc.kLineDataSet = model.twExStockDataSet
vc.volumnDataSet = model.twExVolumeDataSet //前幾篇沒有這個值
navigationController?.pushViewController(vc, animated: true)
}
}
然後,就可以準備在 KLineViewController 中畫上量的圖了。