Migrate from Core Data to SwiftData
- Replace Core Data with SwiftData for iOS 18+ - Create MoodEntryModel as @Model class replacing MoodEntry entity - Create SharedModelContainer for App Group container sharing - Create DataController with CRUD extensions replacing PersistenceController - Update all views and view models to use MoodEntryModel - Update widget extension to use SwiftData - Remove old Core Data files (Persistence*.swift, .xcdatamodeld) - Add EntryType enum with all entry type cases - Fix widget label truncation with proper spacing and text scaling 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
82
Shared/Persisence/DataController.swift
Normal file
82
Shared/Persisence/DataController.swift
Normal file
@@ -0,0 +1,82 @@
|
||||
//
|
||||
// DataController.swift
|
||||
// Feels
|
||||
//
|
||||
// SwiftData controller replacing Core Data PersistenceController.
|
||||
//
|
||||
|
||||
import SwiftData
|
||||
import SwiftUI
|
||||
|
||||
@MainActor
|
||||
final class DataController: ObservableObject {
|
||||
static let shared = DataController()
|
||||
|
||||
private(set) var container: ModelContainer
|
||||
|
||||
var modelContext: ModelContext {
|
||||
container.mainContext
|
||||
}
|
||||
|
||||
private var useCloudKit: Bool {
|
||||
GroupUserDefaults.groupDefaults.bool(forKey: UserDefaultsStore.Keys.useCloudKit.rawValue)
|
||||
}
|
||||
|
||||
// Listeners for data changes (keeping existing pattern)
|
||||
var switchContainerListeners = [(() -> Void)]()
|
||||
private var editedDataClosure = [() -> Void]()
|
||||
|
||||
// Computed properties for earliest/latest entries
|
||||
var earliestEntry: MoodEntryModel? {
|
||||
var descriptor = FetchDescriptor<MoodEntryModel>(
|
||||
sortBy: [SortDescriptor(\.forDate, order: .forward)]
|
||||
)
|
||||
descriptor.fetchLimit = 1
|
||||
return try? modelContext.fetch(descriptor).first
|
||||
}
|
||||
|
||||
var latestEntry: MoodEntryModel? {
|
||||
var descriptor = FetchDescriptor<MoodEntryModel>(
|
||||
sortBy: [SortDescriptor(\.forDate, order: .reverse)]
|
||||
)
|
||||
descriptor.fetchLimit = 1
|
||||
return try? modelContext.fetch(descriptor).first
|
||||
}
|
||||
|
||||
private init() {
|
||||
let cloudKit = GroupUserDefaults.groupDefaults.bool(forKey: UserDefaultsStore.Keys.useCloudKit.rawValue)
|
||||
container = SharedModelContainer.create(useCloudKit: cloudKit)
|
||||
}
|
||||
|
||||
// MARK: - Container Switching (for CloudKit toggle)
|
||||
|
||||
func switchContainer() {
|
||||
save()
|
||||
container = SharedModelContainer.create(useCloudKit: useCloudKit)
|
||||
for listener in switchContainerListeners {
|
||||
listener()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Listener Management
|
||||
|
||||
func addNewDataListener(closure: @escaping (() -> Void)) {
|
||||
editedDataClosure.append(closure)
|
||||
}
|
||||
|
||||
func saveAndRunDataListeners() {
|
||||
save()
|
||||
for closure in editedDataClosure {
|
||||
closure()
|
||||
}
|
||||
}
|
||||
|
||||
func save() {
|
||||
guard modelContext.hasChanges else { return }
|
||||
do {
|
||||
try modelContext.save()
|
||||
} catch {
|
||||
print("Failed to save context: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
77
Shared/Persisence/DataControllerADD.swift
Normal file
77
Shared/Persisence/DataControllerADD.swift
Normal file
@@ -0,0 +1,77 @@
|
||||
//
|
||||
// DataControllerADD.swift
|
||||
// Feels
|
||||
//
|
||||
// SwiftData CREATE operations.
|
||||
//
|
||||
|
||||
import SwiftData
|
||||
import Foundation
|
||||
|
||||
extension DataController {
|
||||
func add(mood: Mood, forDate date: Date, entryType: EntryType) {
|
||||
// Delete existing entry for this date if present
|
||||
if let existing = getEntry(byDate: date) {
|
||||
modelContext.delete(existing)
|
||||
try? modelContext.save()
|
||||
}
|
||||
|
||||
let entry = MoodEntryModel(
|
||||
forDate: date,
|
||||
mood: mood,
|
||||
entryType: entryType
|
||||
)
|
||||
|
||||
modelContext.insert(entry)
|
||||
EventLogger.log(event: "add_entry", withData: ["entry_type": entryType.rawValue])
|
||||
saveAndRunDataListeners()
|
||||
}
|
||||
|
||||
func fillInMissingDates() {
|
||||
let currentOnboarding = UserDefaultsStore.getOnboarding()
|
||||
var endDate = ShowBasedOnVoteLogics.getCurrentVotingDate(onboardingData: currentOnboarding)
|
||||
// Since it's for views, take away the last date so vote is enabled
|
||||
endDate = Calendar.current.date(byAdding: .day, value: -1, to: endDate)!
|
||||
|
||||
let descriptor = FetchDescriptor<MoodEntryModel>(
|
||||
sortBy: [SortDescriptor(\.forDate, order: .reverse)]
|
||||
)
|
||||
|
||||
guard let entries = try? modelContext.fetch(descriptor),
|
||||
let firstEntry = entries.last else { return }
|
||||
|
||||
let allDates: [Date] = Date.dates(from: firstEntry.forDate, toDate: endDate, includingToDate: true).map {
|
||||
Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: $0)!
|
||||
}
|
||||
|
||||
let existingDates: Set<Date> = Set(entries.map {
|
||||
Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: $0.forDate)!
|
||||
})
|
||||
|
||||
let missing = Array(Set(allDates).subtracting(existingDates)).sorted(by: >)
|
||||
|
||||
for date in missing {
|
||||
// Add 12 hours to avoid UTC offset issues
|
||||
let adjustedDate = Calendar.current.date(byAdding: .hour, value: 12, to: date)!
|
||||
add(mood: .missing, forDate: adjustedDate, entryType: .filledInMissing)
|
||||
}
|
||||
|
||||
if !missing.isEmpty {
|
||||
EventLogger.log(event: "filled_in_missing_entries", withData: ["count": missing.count])
|
||||
}
|
||||
}
|
||||
|
||||
func fixWrongWeekdays() {
|
||||
let data = getData(startDate: Date(timeIntervalSince1970: 0), endDate: Date(), includedDays: [])
|
||||
for entry in data {
|
||||
entry.weekDay = Calendar.current.component(.weekday, from: entry.forDate)
|
||||
}
|
||||
save()
|
||||
}
|
||||
|
||||
func removeNoForDates() {
|
||||
// Note: With SwiftData's non-optional forDate, this is essentially a no-op
|
||||
// Keeping for API compatibility
|
||||
EventLogger.log(event: "removed_entry_no_for_date", withData: ["count": 0])
|
||||
}
|
||||
}
|
||||
40
Shared/Persisence/DataControllerDELETE.swift
Normal file
40
Shared/Persisence/DataControllerDELETE.swift
Normal file
@@ -0,0 +1,40 @@
|
||||
//
|
||||
// DataControllerDELETE.swift
|
||||
// Feels
|
||||
//
|
||||
// SwiftData DELETE operations.
|
||||
//
|
||||
|
||||
import SwiftData
|
||||
import Foundation
|
||||
|
||||
extension DataController {
|
||||
func clearDB() {
|
||||
do {
|
||||
try modelContext.delete(model: MoodEntryModel.self)
|
||||
saveAndRunDataListeners()
|
||||
} catch {
|
||||
fatalError("Failed to clear database: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
func deleteLast(numberOfEntries: Int) {
|
||||
let startDate = Calendar.current.date(byAdding: .day, value: -numberOfEntries, to: Date())!
|
||||
let entries = getData(startDate: startDate, endDate: Date(), includedDays: [])
|
||||
|
||||
for entry in entries {
|
||||
modelContext.delete(entry)
|
||||
}
|
||||
save()
|
||||
}
|
||||
|
||||
func deleteRandomFromLast(numberOfEntries: Int) {
|
||||
let startDate = Calendar.current.date(byAdding: .day, value: -numberOfEntries, to: Date())!
|
||||
let entries = getData(startDate: startDate, endDate: Date(), includedDays: [])
|
||||
|
||||
for entry in entries where Bool.random() {
|
||||
modelContext.delete(entry)
|
||||
}
|
||||
save()
|
||||
}
|
||||
}
|
||||
85
Shared/Persisence/DataControllerGET.swift
Normal file
85
Shared/Persisence/DataControllerGET.swift
Normal file
@@ -0,0 +1,85 @@
|
||||
//
|
||||
// DataControllerGET.swift
|
||||
// Feels
|
||||
//
|
||||
// SwiftData READ operations.
|
||||
//
|
||||
|
||||
import SwiftData
|
||||
import Foundation
|
||||
|
||||
extension DataController {
|
||||
func getEntry(byDate date: Date) -> MoodEntryModel? {
|
||||
let startDate = Calendar.current.startOfDay(for: date)
|
||||
let endDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate)!
|
||||
|
||||
var descriptor = FetchDescriptor<MoodEntryModel>(
|
||||
predicate: #Predicate { entry in
|
||||
entry.forDate >= startDate && entry.forDate <= endDate
|
||||
},
|
||||
sortBy: [SortDescriptor(\.forDate, order: .forward)]
|
||||
)
|
||||
descriptor.fetchLimit = 1
|
||||
|
||||
return try? modelContext.fetch(descriptor).first
|
||||
}
|
||||
|
||||
func getData(startDate: Date, endDate: Date, includedDays: [Int]) -> [MoodEntryModel] {
|
||||
let weekDays = includedDays.isEmpty ? [1, 2, 3, 4, 5, 6, 7] : includedDays
|
||||
|
||||
let descriptor = FetchDescriptor<MoodEntryModel>(
|
||||
predicate: #Predicate { entry in
|
||||
entry.forDate >= startDate &&
|
||||
entry.forDate <= endDate &&
|
||||
weekDays.contains(entry.weekDay)
|
||||
},
|
||||
sortBy: [SortDescriptor(\.forDate, order: .forward)]
|
||||
)
|
||||
|
||||
return (try? modelContext.fetch(descriptor)) ?? []
|
||||
}
|
||||
|
||||
func splitIntoYearMonth(includedDays: [Int]) -> [Int: [Int: [MoodEntryModel]]] {
|
||||
let data = getData(
|
||||
startDate: Date(timeIntervalSince1970: 0),
|
||||
endDate: Date(),
|
||||
includedDays: includedDays
|
||||
).sorted { $0.forDate < $1.forDate }
|
||||
|
||||
guard let earliest = data.first,
|
||||
let latest = data.last else { return [:] }
|
||||
|
||||
let calendar = Calendar.current
|
||||
let earliestYear = calendar.component(.year, from: earliest.forDate)
|
||||
let latestYear = calendar.component(.year, from: latest.forDate)
|
||||
|
||||
var result = [Int: [Int: [MoodEntryModel]]]()
|
||||
|
||||
for year in earliestYear...latestYear {
|
||||
var monthData = [Int: [MoodEntryModel]]()
|
||||
|
||||
for month in 1...12 {
|
||||
var components = DateComponents()
|
||||
components.year = year
|
||||
components.month = month
|
||||
components.day = 1
|
||||
|
||||
guard let startOfMonth = calendar.date(from: components) else { continue }
|
||||
|
||||
let items = getData(
|
||||
startDate: startOfMonth,
|
||||
endDate: startOfMonth.endOfMonth,
|
||||
includedDays: [1, 2, 3, 4, 5, 6, 7]
|
||||
)
|
||||
|
||||
if !items.isEmpty {
|
||||
monthData[month] = items
|
||||
}
|
||||
}
|
||||
|
||||
result[year] = monthData
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
93
Shared/Persisence/DataControllerHelper.swift
Normal file
93
Shared/Persisence/DataControllerHelper.swift
Normal file
@@ -0,0 +1,93 @@
|
||||
//
|
||||
// DataControllerHelper.swift
|
||||
// Feels
|
||||
//
|
||||
// SwiftData helper and test data operations.
|
||||
//
|
||||
|
||||
import SwiftData
|
||||
import Foundation
|
||||
|
||||
extension DataController {
|
||||
func randomEntries(count: Int) -> [MoodEntryModel] {
|
||||
var entries = [MoodEntryModel]()
|
||||
|
||||
for idx in 0..<count {
|
||||
let date = Calendar.current.date(byAdding: .day, value: -idx, to: Date())!
|
||||
let entry = MoodEntryModel(
|
||||
forDate: date,
|
||||
mood: Mood.allValues.randomElement()!,
|
||||
entryType: .listView
|
||||
)
|
||||
entry.timestamp = date
|
||||
entries.append(entry)
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
func populateMemory() {
|
||||
#if DEBUG
|
||||
for idx in 1..<255 {
|
||||
let date = Calendar.current.date(byAdding: .day, value: -idx, to: Date())!
|
||||
var moodValue = Int.random(in: 2...4)
|
||||
if idx % 5 == 0 {
|
||||
moodValue = Int.random(in: 0...4)
|
||||
}
|
||||
|
||||
let entry = MoodEntryModel(
|
||||
forDate: date,
|
||||
mood: Mood(rawValue: moodValue) ?? .average,
|
||||
entryType: .listView
|
||||
)
|
||||
entry.timestamp = date
|
||||
modelContext.insert(entry)
|
||||
}
|
||||
save()
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Creates an entry that is NOT inserted into the context - used for UI placeholders
|
||||
func generateObjectNotInArray(forDate date: Date = Date(), withMood mood: Mood = .placeholder) -> MoodEntryModel {
|
||||
var moodValue = Int.random(in: 2...4)
|
||||
if Int.random(in: 0...400) % 5 == 0 {
|
||||
moodValue = Int.random(in: 0...4)
|
||||
}
|
||||
|
||||
let entry = MoodEntryModel(
|
||||
forDate: date,
|
||||
moodValue: moodValue,
|
||||
entryType: EntryType.listView.rawValue,
|
||||
canEdit: false,
|
||||
canDelete: false
|
||||
)
|
||||
return entry
|
||||
}
|
||||
|
||||
func populateTestData() {
|
||||
clearDB()
|
||||
|
||||
for idx in 1..<1000 {
|
||||
let date = Calendar.current.date(byAdding: .day, value: -idx, to: Date())!
|
||||
var moodValue = Int.random(in: 3...4)
|
||||
if Int.random(in: 0...400) % 5 == 0 {
|
||||
moodValue = Int.random(in: 0...4)
|
||||
}
|
||||
|
||||
let entry = MoodEntryModel(
|
||||
forDate: date,
|
||||
mood: Mood(rawValue: moodValue) ?? .average,
|
||||
entryType: .listView
|
||||
)
|
||||
modelContext.insert(entry)
|
||||
}
|
||||
|
||||
saveAndRunDataListeners()
|
||||
}
|
||||
|
||||
func longestStreak() -> [MoodEntryModel] {
|
||||
let descriptor = FetchDescriptor<MoodEntryModel>(
|
||||
sortBy: [SortDescriptor(\.forDate, order: .forward)]
|
||||
)
|
||||
return (try? modelContext.fetch(descriptor)) ?? []
|
||||
}
|
||||
}
|
||||
24
Shared/Persisence/DataControllerUPDATE.swift
Normal file
24
Shared/Persisence/DataControllerUPDATE.swift
Normal file
@@ -0,0 +1,24 @@
|
||||
//
|
||||
// DataControllerUPDATE.swift
|
||||
// Feels
|
||||
//
|
||||
// SwiftData UPDATE operations.
|
||||
//
|
||||
|
||||
import SwiftData
|
||||
import Foundation
|
||||
|
||||
extension DataController {
|
||||
@discardableResult
|
||||
func update(entryDate: Date, withMood mood: Mood) -> Bool {
|
||||
guard let entry = getEntry(byDate: entryDate) else {
|
||||
return false
|
||||
}
|
||||
|
||||
entry.moodValue = mood.rawValue
|
||||
saveAndRunDataListeners()
|
||||
|
||||
EventLogger.log(event: "update_entry")
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
//
|
||||
// Persistence.swift
|
||||
// Shared
|
||||
//
|
||||
// Created by Trey Tartt on 1/5/22.
|
||||
//
|
||||
|
||||
import CoreData
|
||||
import SwiftUI
|
||||
|
||||
class PersistenceController {
|
||||
@AppStorage(UserDefaultsStore.Keys.useCloudKit.rawValue, store: GroupUserDefaults.groupDefaults)
|
||||
|
||||
private var useCloudKit = false
|
||||
|
||||
static let shared = PersistenceController.persistenceController
|
||||
|
||||
private static var persistenceController: PersistenceController {
|
||||
return PersistenceController(inMemory: true)
|
||||
}
|
||||
|
||||
public var viewContext: NSManagedObjectContext {
|
||||
return PersistenceController.shared.container.viewContext
|
||||
}
|
||||
|
||||
public lazy var childContext: NSManagedObjectContext = {
|
||||
NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
|
||||
}()
|
||||
|
||||
public var switchContainerListeners = [(() -> Void)]()
|
||||
|
||||
private var editedDataClosure = [() -> Void]()
|
||||
|
||||
public var earliestEntry: MoodEntry? {
|
||||
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
|
||||
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "forDate", ascending: true)]
|
||||
let first = try! viewContext.fetch(fetchRequest).first
|
||||
return first ?? nil
|
||||
}
|
||||
|
||||
public var latestEntry: MoodEntry? {
|
||||
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
|
||||
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "forDate", ascending: true)]
|
||||
let last = try! viewContext.fetch(fetchRequest).last
|
||||
return last ?? nil
|
||||
}
|
||||
|
||||
lazy var container: NSPersistentContainer = {
|
||||
setupContainer()
|
||||
}()
|
||||
|
||||
func switchContainer() {
|
||||
try? viewContext.save()
|
||||
container = setupContainer()
|
||||
for item in switchContainerListeners {
|
||||
item()
|
||||
}
|
||||
}
|
||||
|
||||
public func addNewDataListener(closure: @escaping (() -> Void)) {
|
||||
editedDataClosure.append(closure)
|
||||
}
|
||||
|
||||
public func saveAndRunDataListerners() {
|
||||
do {
|
||||
try viewContext.save()
|
||||
|
||||
for closure in editedDataClosure {
|
||||
closure()
|
||||
}
|
||||
} catch {
|
||||
print(error)
|
||||
}
|
||||
}
|
||||
|
||||
private func setupContainer() -> NSPersistentContainer {
|
||||
if useCloudKit {
|
||||
container = NSPersistentCloudKitContainer(name: "Feels")
|
||||
} else {
|
||||
container = NSCustomPersistentContainer(name: "Feels")
|
||||
}
|
||||
|
||||
for description in container.persistentStoreDescriptions {
|
||||
description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
|
||||
description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
|
||||
description.setOption(true as NSNumber, forKey: NSMigratePersistentStoresAutomaticallyOption)
|
||||
description.setOption(true as NSNumber, forKey: NSInferMappingModelAutomaticallyOption)
|
||||
}
|
||||
|
||||
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
|
||||
self.container.viewContext.automaticallyMergesChangesFromParent = true
|
||||
|
||||
if let error = error as NSError? {
|
||||
fatalError("Unresolved error \(error), \(error.userInfo)")
|
||||
}
|
||||
})
|
||||
|
||||
return container
|
||||
}
|
||||
|
||||
init(inMemory: Bool = false) {
|
||||
container = setupContainer()
|
||||
}
|
||||
}
|
||||
|
||||
extension NSManagedObjectContext {
|
||||
/// Executes the given `NSBatchDeleteRequest` and directly merges the changes to bring the given managed object context up to date.
|
||||
///
|
||||
/// - Parameter batchDeleteRequest: The `NSBatchDeleteRequest` to execute.
|
||||
/// - Throws: An error if anything went wrong executing the batch deletion.
|
||||
public func executeAndMergeChanges(using batchDeleteRequest: NSBatchDeleteRequest) throws {
|
||||
batchDeleteRequest.resultType = .resultTypeObjectIDs
|
||||
let result = try execute(batchDeleteRequest) as? NSBatchDeleteResult
|
||||
let changes: [AnyHashable: Any] = [NSDeletedObjectsKey: result?.result as? [NSManagedObjectID] ?? []]
|
||||
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [self])
|
||||
}
|
||||
}
|
||||
|
||||
class NSCustomPersistentContainer: NSPersistentContainer {
|
||||
override open class func defaultDirectoryURL() -> URL {
|
||||
#if DEBUG
|
||||
if let storeURLDebug = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Constants.groupShareIdDebug) {
|
||||
return storeURLDebug.appendingPathComponent("Feels-Debug.sqlite")
|
||||
}
|
||||
// Fallback to default location if App Group not available
|
||||
print("⚠️ App Group not available, using default Core Data location")
|
||||
return super.defaultDirectoryURL()
|
||||
#else
|
||||
if let storeURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Constants.groupShareId) {
|
||||
return storeURL.appendingPathComponent("Feels.sqlite")
|
||||
}
|
||||
// Fallback to default location if App Group not available
|
||||
print("⚠️ App Group not available, using default Core Data location")
|
||||
return super.defaultDirectoryURL()
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
//
|
||||
// PersistenceADD.swift
|
||||
// Feels
|
||||
//
|
||||
// Created by Trey Tartt on 2/17/22.
|
||||
//
|
||||
|
||||
import CoreData
|
||||
|
||||
extension PersistenceController {
|
||||
public func fixWrongWeekdays() {
|
||||
let data = PersistenceController.shared.getData(startDate: Date(timeIntervalSince1970: 0),
|
||||
endDate: Date(),
|
||||
includedDays: []).sorted(by: {
|
||||
$0.forDate! < $1.forDate!
|
||||
})
|
||||
|
||||
data.forEach({
|
||||
$0.weekDay = Int16(Calendar.current.component(.weekday, from: $0.forDate!))
|
||||
})
|
||||
try? viewContext.save()
|
||||
}
|
||||
|
||||
public func add(mood: Mood, forDate date: Date, entryType: EntryType) {
|
||||
if let existingEntry = getEntry(byDate: date) {
|
||||
viewContext.delete(existingEntry)
|
||||
try? viewContext.save()
|
||||
}
|
||||
|
||||
let newItem = MoodEntry(context: viewContext)
|
||||
newItem.timestamp = Date()
|
||||
newItem.moodValue = Int16(mood.rawValue)
|
||||
newItem.forDate = date
|
||||
newItem.weekDay = Int16(Calendar.current.component(.weekday, from: date))
|
||||
newItem.canEdit = true
|
||||
newItem.canDelete = true
|
||||
newItem.entryType = Int16(entryType.rawValue)
|
||||
|
||||
EventLogger.log(event: "add_entry", withData: ["entry_type": entryType.rawValue])
|
||||
|
||||
saveAndRunDataListerners()
|
||||
}
|
||||
|
||||
func fillInMissingDates() {
|
||||
let currentOnboarding = UserDefaultsStore.getOnboarding()
|
||||
var endDate = ShowBasedOnVoteLogics.getCurrentVotingDate(onboardingData: currentOnboarding)
|
||||
// since its for views take away the last date so vote is enabled
|
||||
endDate = Calendar.current.date(byAdding: .day, value: -1, to: endDate)!
|
||||
|
||||
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
|
||||
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "forDate", ascending: false)]
|
||||
let entries = try! viewContext.fetch(fetchRequest)
|
||||
|
||||
if let firstEntry = entries.last?.forDate {
|
||||
let allDates: [Date] = Date.dates(from: firstEntry, toDate: endDate, includingToDate: true).map({
|
||||
let zeroDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: $0)!
|
||||
return zeroDate
|
||||
})
|
||||
|
||||
let existingEntries: [Date] = entries.compactMap({
|
||||
if let date = $0.forDate {
|
||||
let zeroDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: date)!
|
||||
return zeroDate
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
let allDatesSet = Set(allDates)
|
||||
let existingEntriesSet = Set(existingEntries)
|
||||
let missing = Array(allDatesSet.subtracting(existingEntriesSet)).sorted(by: >)
|
||||
for date in missing {
|
||||
// add 12 hours, if you enter a things right at 12:00.00 it wont show .... mabye
|
||||
// due to utc offset?
|
||||
let adjustedDate = Calendar.current.date(byAdding: .hour, value: 12, to: date)!
|
||||
add(mood: .missing, forDate: adjustedDate, entryType: .filledInMissing)
|
||||
}
|
||||
|
||||
if !missing.isEmpty {
|
||||
EventLogger.log(event: "filled_in_missing_entries", withData: ["count": missing.count])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func removeNoForDates() {
|
||||
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
|
||||
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "forDate", ascending: false)]
|
||||
let entries = try! viewContext.fetch(fetchRequest)
|
||||
|
||||
for entry in entries {
|
||||
guard let _ = entry.forDate else {
|
||||
viewContext.delete(entry)
|
||||
try? viewContext.save()
|
||||
return
|
||||
}
|
||||
}
|
||||
EventLogger.log(event: "removed_entry_no_for_date", withData: ["count": entries.count])
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
//
|
||||
// PersistenceDELETE.swift
|
||||
// Feels
|
||||
//
|
||||
// Created by Trey Tartt on 2/17/22.
|
||||
//
|
||||
|
||||
import CoreData
|
||||
|
||||
extension PersistenceController {
|
||||
func clearDB() {
|
||||
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "MoodEntry")
|
||||
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
|
||||
|
||||
do {
|
||||
try viewContext.executeAndMergeChanges(using: deleteRequest)
|
||||
saveAndRunDataListerners()
|
||||
} catch let error as NSError {
|
||||
fatalError("Unresolved error \(error), \(error.userInfo)")
|
||||
}
|
||||
}
|
||||
|
||||
func deleteLast(numberOfEntries: Int) {
|
||||
let entries = PersistenceController.shared.getData(startDate: Calendar.current.date(byAdding: .day, value: -numberOfEntries, to: Date())!,
|
||||
endDate: Date(),
|
||||
includedDays: [])
|
||||
for entry in entries {
|
||||
viewContext.delete(entry)
|
||||
}
|
||||
try! viewContext.save()
|
||||
}
|
||||
|
||||
func deleteRandomFromLast(numberOfEntries: Int) {
|
||||
let entries = PersistenceController.shared.getData(startDate: Calendar.current.date(byAdding: .day, value: -numberOfEntries, to: Date())!,
|
||||
endDate: Date(),
|
||||
includedDays: [])
|
||||
for entry in entries {
|
||||
if Bool.random() {
|
||||
viewContext.delete(entry)
|
||||
}
|
||||
}
|
||||
try! viewContext.save()
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
//
|
||||
// PersistenceGET.swift
|
||||
// Feels
|
||||
//
|
||||
// Created by Trey Tartt on 2/17/22.
|
||||
//
|
||||
|
||||
import CoreData
|
||||
|
||||
extension PersistenceController {
|
||||
public func getEntry(byDate date: Date) -> MoodEntry? {
|
||||
let startDate = Calendar.current.startOfDay(for: date)
|
||||
let endDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate)!
|
||||
|
||||
let predicate = NSPredicate(format: "forDate >= %@ && forDate <= %@ ",
|
||||
startDate as NSDate,
|
||||
endDate as NSDate)
|
||||
|
||||
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
|
||||
fetchRequest.predicate = predicate
|
||||
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "forDate", ascending: true)]
|
||||
let data = try! viewContext.fetch(fetchRequest)
|
||||
return data.first
|
||||
}
|
||||
|
||||
public func getData(startDate: Date, endDate: Date, includedDays: [Int]) -> [MoodEntry] {
|
||||
try! viewContext.setQueryGenerationFrom(.current)
|
||||
// viewContext.refreshAllObjects()
|
||||
|
||||
var includedDays16 = [Int16]()
|
||||
|
||||
if includedDays.isEmpty {
|
||||
includedDays16 = [Int16(1), Int16(2), Int16(3), Int16(4), Int16(5), Int16(6), Int16(7)]
|
||||
} else {
|
||||
includedDays16 = includedDays.map({
|
||||
Int16($0)
|
||||
})
|
||||
}
|
||||
let predicate = NSPredicate(format: "forDate >= %@ && forDate <= %@ && weekDay IN %@",
|
||||
startDate as NSDate,
|
||||
endDate as NSDate,
|
||||
includedDays16)
|
||||
|
||||
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
|
||||
fetchRequest.predicate = predicate
|
||||
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "forDate", ascending: true)]
|
||||
let data = try! viewContext.fetch(fetchRequest)
|
||||
return data
|
||||
}
|
||||
|
||||
public func splitIntoYearMonth(includedDays: [Int]) -> [Int: [Int: [MoodEntry]]] {
|
||||
let data = PersistenceController.shared.getData(startDate: Date(timeIntervalSince1970: 0),
|
||||
endDate: Date(),
|
||||
includedDays: includedDays).sorted(by: {
|
||||
$0.forDate! < $1.forDate!
|
||||
})
|
||||
var returnData = [Int: [Int: [MoodEntry]]]()
|
||||
|
||||
if let earliestEntry = data.first,
|
||||
let lastEntry = data.last {
|
||||
|
||||
let calendar = Calendar.current
|
||||
let components = calendar.dateComponents([.year], from: earliestEntry.forDate!)
|
||||
let earliestYear = components.year!
|
||||
|
||||
let latestComponents = calendar.dateComponents([.year], from: lastEntry.forDate!)
|
||||
let latestYear = latestComponents.year!
|
||||
|
||||
for year in earliestYear...latestYear {
|
||||
var allMonths = [Int: [MoodEntry]]()
|
||||
|
||||
for month in (1...12) {
|
||||
var components = DateComponents()
|
||||
components.month = month
|
||||
components.year = year
|
||||
components.day = 1
|
||||
let startDateOfMonth = Calendar.current.date(from: components)!
|
||||
|
||||
let items = PersistenceController.shared.getData(startDate: startDateOfMonth,
|
||||
endDate: startDateOfMonth.endOfMonth,
|
||||
includedDays: [1,2,3,4,5,6,7])
|
||||
|
||||
if !items.isEmpty {
|
||||
allMonths[month] = items
|
||||
}
|
||||
}
|
||||
returnData[year] = allMonths
|
||||
}
|
||||
}
|
||||
return returnData
|
||||
}
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
//
|
||||
// PersistenceHelper.swift
|
||||
// Feels (iOS)
|
||||
//
|
||||
// Created by Trey Tartt on 2/17/22.
|
||||
//
|
||||
|
||||
import CoreData
|
||||
|
||||
extension PersistenceController {
|
||||
public func randomEntries(count: Int) -> [MoodEntry] {
|
||||
var entries = [MoodEntry]()
|
||||
|
||||
for idx in 0..<count {
|
||||
let newItem = MoodEntry(context: childContext)
|
||||
newItem.timestamp = Calendar.current.date(byAdding: .day, value: -idx, to: Date())
|
||||
newItem.moodValue = Int16(Mood.allValues.randomElement()!.rawValue)
|
||||
let date = Calendar.current.date(byAdding: .day, value: -idx, to: Date())!
|
||||
newItem.forDate = date
|
||||
newItem.weekDay = Int16(Calendar.current.component(.weekday, from: date))
|
||||
newItem.canEdit = true
|
||||
newItem.canDelete = true
|
||||
entries.append(newItem)
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
func populateMemory() {
|
||||
#if debug
|
||||
for idx in 1..<255 {
|
||||
let newItem = MoodEntry(context: viewContext)
|
||||
newItem.timestamp = Calendar.current.date(byAdding: .day, value: -idx, to: Date())
|
||||
newItem.moodValue = Int16.random(in: 2 ... 4)
|
||||
if idx % 5 == 0 {
|
||||
newItem.moodValue = Int16.random(in: 0 ... 4)
|
||||
}
|
||||
newItem.canEdit = true
|
||||
newItem.canDelete = true
|
||||
|
||||
let date = Calendar.current.date(byAdding: .day, value: -idx, to: Date())!
|
||||
newItem.forDate = date
|
||||
newItem.weekDay = Int16(Calendar.current.component(.weekday, from: date))
|
||||
}
|
||||
do {
|
||||
try viewContext.save()
|
||||
} catch {
|
||||
// Replace this implementation with code to handle the error appropriately.
|
||||
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
|
||||
let nsError = error as NSError
|
||||
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
func generateObjectNotInArray(forDate date: Date = Date(), withMood mood: Mood = .placeholder) -> MoodEntry {
|
||||
let newItem = MoodEntry(context: childContext)
|
||||
newItem.timestamp = Date()
|
||||
newItem.moodValue = Int16.random(in: 2 ... 4)
|
||||
if Int16.random(in: 0 ... 400) % 5 == 0 {
|
||||
newItem.moodValue = Int16.random(in: 0 ... 4)
|
||||
}
|
||||
newItem.forDate = date
|
||||
newItem.weekDay = Int16(Calendar.current.component(.weekday, from: Date()))
|
||||
newItem.canEdit = false
|
||||
newItem.canDelete = false
|
||||
return newItem
|
||||
}
|
||||
|
||||
func populateTestData() {
|
||||
do {
|
||||
self.clearDB()
|
||||
try viewContext.save()
|
||||
|
||||
for idx in 1..<1000 {
|
||||
let newItem = MoodEntry(context: viewContext)
|
||||
newItem.timestamp = Date()
|
||||
newItem.moodValue = Int16.random(in: 3 ... 4)
|
||||
if Int16.random(in: 0 ... 400) % 5 == 0 {
|
||||
newItem.moodValue = Int16.random(in: 0 ... 4)
|
||||
}
|
||||
newItem.canEdit = true
|
||||
newItem.canDelete = true
|
||||
|
||||
let date = Calendar.current.date(byAdding: .day, value: -idx, to: Date())!
|
||||
newItem.forDate = date
|
||||
newItem.weekDay = Int16(Calendar.current.component(.weekday, from: date))
|
||||
}
|
||||
|
||||
saveAndRunDataListerners()
|
||||
} catch {
|
||||
// Replace this implementation with code to handle the error appropriately.
|
||||
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
|
||||
let nsError = error as NSError
|
||||
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
|
||||
}
|
||||
}
|
||||
|
||||
func longestStreak() -> [MoodEntry] {
|
||||
// let predicate = NSPredicate(format: "forDate == %@", date as NSDate)
|
||||
|
||||
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
|
||||
// fetchRequest.predicate = predicate
|
||||
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "forDate", ascending: true)]
|
||||
let data = try! viewContext.fetch(fetchRequest)
|
||||
return data
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
//
|
||||
// PersistenceUPDATE.swift
|
||||
// Feels
|
||||
//
|
||||
// Created by Trey Tartt on 2/18/22.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
extension PersistenceController {
|
||||
@discardableResult
|
||||
public func update(entryDate: Date, withModd mood: Mood) -> Bool {
|
||||
guard let existingEntry = getEntry(byDate: entryDate) else {
|
||||
return false
|
||||
}
|
||||
|
||||
existingEntry.setValue(mood.rawValue, forKey: "moodValue")
|
||||
saveAndRunDataListerners()
|
||||
|
||||
EventLogger.log(event: "update_entry")
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
79
Shared/Persisence/SharedModelContainer.swift
Normal file
79
Shared/Persisence/SharedModelContainer.swift
Normal file
@@ -0,0 +1,79 @@
|
||||
//
|
||||
// SharedModelContainer.swift
|
||||
// Feels
|
||||
//
|
||||
// Factory for creating ModelContainer shared between main app and widget extension.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import SwiftData
|
||||
|
||||
enum SharedModelContainer {
|
||||
/// Creates a ModelContainer with the appropriate configuration for app group sharing
|
||||
/// - Parameter useCloudKit: Whether to enable CloudKit sync
|
||||
/// - Returns: Configured ModelContainer
|
||||
static func create(useCloudKit: Bool = false) -> ModelContainer {
|
||||
let schema = Schema([MoodEntryModel.self])
|
||||
let storeURL = Self.storeURL
|
||||
|
||||
let configuration: ModelConfiguration
|
||||
if useCloudKit {
|
||||
// CloudKit-enabled configuration
|
||||
configuration = ModelConfiguration(
|
||||
schema: schema,
|
||||
url: storeURL,
|
||||
cloudKitDatabase: .private(cloudKitContainerID)
|
||||
)
|
||||
} else {
|
||||
// Local-only configuration
|
||||
configuration = ModelConfiguration(
|
||||
schema: schema,
|
||||
url: storeURL,
|
||||
cloudKitDatabase: .none
|
||||
)
|
||||
}
|
||||
|
||||
do {
|
||||
return try ModelContainer(for: schema, configurations: [configuration])
|
||||
} catch {
|
||||
fatalError("Failed to create ModelContainer: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// The URL for the SwiftData store in the shared app group container
|
||||
static var storeURL: URL {
|
||||
guard let containerURL = FileManager.default.containerURL(
|
||||
forSecurityApplicationGroupIdentifier: appGroupID
|
||||
) else {
|
||||
fatalError("App Group container not available for: \(appGroupID)")
|
||||
}
|
||||
return containerURL.appendingPathComponent(storeFileName)
|
||||
}
|
||||
|
||||
/// App Group identifier based on build configuration
|
||||
static var appGroupID: String {
|
||||
#if DEBUG
|
||||
return Constants.groupShareIdDebug
|
||||
#else
|
||||
return Constants.groupShareId
|
||||
#endif
|
||||
}
|
||||
|
||||
/// CloudKit container identifier based on build configuration
|
||||
static var cloudKitContainerID: String {
|
||||
#if DEBUG
|
||||
return "iCloud.com.tt.ifeelDebug"
|
||||
#else
|
||||
return "iCloud.com.tt.ifeel"
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Store file name based on build configuration
|
||||
static var storeFileName: String {
|
||||
#if DEBUG
|
||||
return "Feels-Debug.store"
|
||||
#else
|
||||
return "Feels.store"
|
||||
#endif
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user