]> git.r.bdr.sh - rbdr/captura/blob - Captura/Data/Persistence.swift
3ae66c351efddb623238540d4d7c1e6bd3c414b7
[rbdr/captura] / Captura / Data / Persistence.swift
1 /*
2 Copyright (C) 2024 Rubén Beltrán del Río
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see https://captura.tranquil.systems.
16 */
17 import CoreData
18
19 struct PersistenceController {
20 static let shared = PersistenceController()
21
22 static var preview: PersistenceController = {
23 let result = PersistenceController(inMemory: true)
24 return result
25 }()
26
27 let container: NSPersistentCloudKitContainer
28
29 init(inMemory: Bool = false) {
30 container = NSPersistentCloudKitContainer(name: "Captura")
31
32 #if DEBUG
33 do {
34 // Use the container to initialize the development schema.
35 try container.initializeCloudKitSchema(options: [])
36 } catch {
37 // Handle any errors.
38 }
39 #endif
40
41 if inMemory {
42 container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
43 }
44 container.loadPersistentStores(completionHandler: { (storeDescription, error) in
45 if let error = error as NSError? {
46 // Replace this implementation with code to handle the error appropriately.
47 // 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.
48
49 /*
50 Typical reasons for an error here include:
51 * The parent directory does not exist, cannot be created, or disallows writing.
52 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
53 * The device is out of space.
54 * The store could not be migrated to the current model version.
55 Check the error message to determine what the actual problem was.
56 */
57 fatalError("Unresolved error \(error), \(error.userInfo)")
58 }
59 })
60 container.viewContext.automaticallyMergesChangesFromParent = true
61 }
62 }