承上一篇,我打算在 App 的 didFinishLaunch 就发动拉取全台股上市日成交资料,并在拉取成功後存入 UserDefatuls。
先设立一个 UserDefaultsKey 的类别,进行 key 的管理。
import Foundation
struct UserDefaultsKey {
static var twAllMarketDayPrice: String {
return "twAllMarketDayPrice"
}
}
然後在 AppDelegate 加上存入 day price tick 的 func。整个 AppDelegate 程序码如下。
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
private lazy var stockDayPriceManager: StockDayPriceManager = {
return StockDayPriceManager()
}()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
stockDayPriceManager.getAllTwMarketStockDayPrice { [weak self] result in
switch result {
case .success(let ticks):
self?.save(twAllMarketTicks: ticks)
case .failure(let error):
print("fetch all tw market stock day price got error: \(error.localizedDescription)")
}
}
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
private func save(twAllMarketTicks: [StockDayTick]) {
if let data = try? JSONEncoder().encode(twAllMarketTicks) {
let key = UserDefaultsKey.twAllMarketDayPrice
UserDefaults.standard.setValue(data, forKey: key)
}
}
}
但後来发现, StockDayPriceManager 的 AlamofireAdapter 最好存起来,如果单纯 init 使用,在 didFinishLaunch 的时候,在模拟器上跑, session 可能已经被回收了,导致下载档案失败
struct StockDayPriceManager {
private var alamofireAdapter: AlamofireAdapter = {
return AlamofireAdapter()
}()
}
下一步,就是在申购页面,进行价差的计算。
台股申购日历
IT铁人赛Demo App
下方是这次 D1 ~ D12 的完成品,可以下载来试
App Store - 台股申购日历
<<: Day27 - 在 Next.js 如何正确地使用 dynamic import
>>: Day27 - 云端交易主机 - Ubuntu SSH登入 & 远端桌面
今天难得有足够的时间可在Dungeon的专案进行调整,本来是想将时间花在整理行为的部份,但一直觉得目...
书同文,车同轨, 听说召唤恶魔时,需要与恶魔签订契约, 契约内容双方都得遵守, C#也拥有跟类别签订...
若是键盘没有之前教的设定 next 与 go 的机制 打完字过後键盘就会收不起来 这边来跟大家分享...
前情提要 艾草:「来,接球!」 (我看着眼前一颗球飞了过来,正准备伸出手接时,突然变成了两颗。) 「...
前言 随着时间的流逝,整个活动也接近了尾声,但在真正结束前都还是要好好地发表,今天笔者想为各位介绍一...