117 lines
3.9 KiB
Swift
117 lines
3.9 KiB
Swift
import SwiftUI
|
||
import UIKit
|
||
import SwiftData
|
||
|
||
@main
|
||
struct WakeApp: App {
|
||
@StateObject private var router = Router.shared
|
||
@StateObject private var authState = AuthState.shared
|
||
@State private var showSplash = true
|
||
|
||
// 使用更简单的方式创建模型容器
|
||
let container: ModelContainer
|
||
|
||
init() {
|
||
do {
|
||
// 1. 先尝试正常加载
|
||
container = try ModelContainer(for: Login.self)
|
||
} catch {
|
||
// 2. 如果失败,尝试删除旧的存储文件
|
||
let url = URL.applicationSupportDirectory.appending(path: "default.store")
|
||
if FileManager.default.fileExists(atPath: url.path) {
|
||
try? FileManager.default.removeItem(at: url)
|
||
}
|
||
|
||
// 3. 重新创建容器
|
||
container = try! ModelContainer(for: Login.self)
|
||
}
|
||
|
||
// 配置网络层
|
||
configureNetwork()
|
||
}
|
||
|
||
var body: some Scene {
|
||
WindowGroup {
|
||
ZStack {
|
||
if showSplash {
|
||
// 显示启动页
|
||
SplashView()
|
||
.environmentObject(authState)
|
||
.onAppear {
|
||
// 启动页显示时检查token有效性
|
||
checkTokenValidity()
|
||
}
|
||
} else {
|
||
// 根据登录状态显示不同视图
|
||
if authState.isAuthenticated {
|
||
// 已登录:显示主页面
|
||
NavigationStack(path: $router.path) {
|
||
// FIXME 调回来
|
||
BlindBoxView(mediaType: .all)
|
||
.navigationDestination(for: AppRoute.self) { route in
|
||
route.view
|
||
}
|
||
// UserInfo()
|
||
// .navigationDestination(for: AppRoute.self) { route in
|
||
// route.view
|
||
// }
|
||
}
|
||
} else {
|
||
// 未登录:显示登录界面
|
||
NavigationStack(path: $router.path) {
|
||
LoginView()
|
||
.navigationDestination(for: AppRoute.self) { route in
|
||
route.view
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
.environmentObject(router)
|
||
.environmentObject(authState)
|
||
.onAppear {
|
||
//2秒后自动隐藏启动页
|
||
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
|
||
withAnimation {
|
||
showSplash = false
|
||
}
|
||
}
|
||
}
|
||
.modelContainer(container)
|
||
}
|
||
}
|
||
|
||
// MARK: - 私有方法
|
||
|
||
/// 配置网络层
|
||
private func configureNetwork() {
|
||
// 配置网络请求超时时间等
|
||
let configuration = URLSessionConfiguration.default
|
||
configuration.timeoutIntervalForRequest = 30
|
||
configuration.timeoutIntervalForResource = 60
|
||
|
||
// 可以在这里添加其他网络配置
|
||
}
|
||
|
||
/// 检查token有效性
|
||
private func checkTokenValidity() {
|
||
guard TokenManager.shared.hasToken,
|
||
let token = KeychainHelper.getAccessToken() else {
|
||
showSplash = false
|
||
return
|
||
}
|
||
|
||
// 检查token是否有效
|
||
if TokenManager.shared.isTokenValid(token) {
|
||
authState.isAuthenticated = true
|
||
}
|
||
|
||
// 2秒后自动隐藏启动页
|
||
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
|
||
withAnimation {
|
||
showSplash = false
|
||
}
|
||
}
|
||
}
|
||
}
|