diff --git a/dimensionhub/Core/UserModel.swift b/dimensionhub/Core/UserModel.swift index 0e26ccb..45a7d76 100644 --- a/dimensionhub/Core/UserModel.swift +++ b/dimensionhub/Core/UserModel.swift @@ -7,15 +7,29 @@ import Foundation import SwiftData +import UIKit @Model final class UserModel { - var userId: Int + var userId: String var username: String - init(userId: Int, username: String) { + init(userId: String, username: String) { self.userId = userId self.username = username } + static func defaultUser() -> UserModel { + return UserModel(userId: getUserId(), username: "") + } + + // 获取设备的唯一标识 + private static func getUserId() -> String { + if let uuid = UIDevice.current.identifierForVendor?.uuidString { + return uuid.lowercased() + } else { + return UUID().uuidString.lowercased() + } + } + } diff --git a/dimensionhub/Views/IndexView.swift b/dimensionhub/Views/IndexView.swift index 761b542..013be18 100644 --- a/dimensionhub/Views/IndexView.swift +++ b/dimensionhub/Views/IndexView.swift @@ -110,7 +110,7 @@ final class IndexModel { struct IndexView: View { @Environment(\.modelContext) private var modelContext - @Query private var items: [Item] + //@Query private var items: [Item] @Query private var userModel: [UserModel] @State var indexModel = IndexModel() @@ -229,22 +229,23 @@ struct IndexView: View { .ignoresSafeArea(edges: .bottom) .task { //await self.indexModel.loadData() + print(userModel) } } private func addItem() { - withAnimation { - let newItem = Item(timestamp: Date()) - modelContext.insert(newItem) - } +// withAnimation { +// let newItem = Item(timestamp: Date()) +// modelContext.insert(newItem) +// } } private func deleteItems(offsets: IndexSet) { - withAnimation { - for index in offsets { - modelContext.delete(items[index]) - } - } +// withAnimation { +// for index in offsets { +// modelContext.delete(items[index]) +// } +// } } } diff --git a/dimensionhub/dimensionhubApp.swift b/dimensionhub/dimensionhubApp.swift index 1bab17f..32c60b9 100644 --- a/dimensionhub/dimensionhubApp.swift +++ b/dimensionhub/dimensionhubApp.swift @@ -15,10 +15,24 @@ struct dimensionhubApp: App { Item.self, UserModel.self ]) - let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) - + let modelConfiguration = ModelConfiguration( + schema: schema, + isStoredInMemoryOnly: false, + allowsSave: true + ) + do { - return try ModelContainer(for: schema, configurations: [modelConfiguration]) + let container = try ModelContainer(for: schema, configurations: [modelConfiguration]) + + // 如何用户不存在,则初始化一个用户 + var descriptor = FetchDescriptor(sortBy: []) + descriptor.fetchLimit = 1 + let users = try container.mainContext.fetch(descriptor) + if users.isEmpty { + container.mainContext.insert(UserModel.defaultUser()) + } + + return container } catch { fatalError("Could not create ModelContainer: \(error)") }