承上一篇,我打算在 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 - 台股申購日曆