Backing up master data locally and restoring from backup - Swift

I am trying to find any information about backing up master data. My ultimate goal is to allow the user to create multiple backups and restore from the selected backup.

I found a sample project that allows you to backup / restore locally or through iCloud in Objective-C, but nothing in swift.

Can anyone help? Or point me in the right direction. I don’t even know where to start.

+10
source share
3 answers

I never had to do this, but if I did this, then I would.

:

  • Core Data. NSPersistentContainer ( ) NSPersistentStoreCoordinator.
  • NSPersistentStoreCoordinator migratePersistentStore(_:to:options:withType:) . URL- , UUID . .
  • . UserDefaults , .

# 2 Core Data - # 1. , , , .

NSPersistentContainer, persistentStoreCoordinator № 2.

, , . , - . NSPersistentContainer. , . , , , , , , , .

, ,

  • .
  • NSPersistentStoreCoordinator .
  • replacePersistentStore(at:destinationOptions:withPersistentStoreFrom:sourceOptions:ofType:) . - , - , .
  • () NSPersistentStoreCoordinator destroyPersistentStore(at:ofType:options:), .
  • NSPersistentContainer .

API, , FileManager . Core Data , , .

+15

: , CloudKit iCloud .

0

Apple. .

Swift 5

    /// Backing up store type to a new and unique location
    /// The method is illustrated in the following code fragment, which shows how you can use migratePersistentStore to take a back up of a store and save it from one location to another.
    /// If the old store type is XML, the example also converts the store to SQLite.
    /// - Parameters:
    ///   - path: Where you want the backup to be done, please create a new unique directory with timestamp or the guid
    ///   - completion: Passes error in case of error or pass nil in case of success
     class func backUpCoreDataFiles(path : URL, completion : @escaping (_ error : String?) -> ())
        {

            // Every time new container is a must as migratePersistentStore method will loose the reference to the container on migration
            let container = NSPersistentContainer(name : "EvolutionPlatform")
            container.loadPersistentStores
                { (storeDescription, error) in
                    if let error = error
                    {
                        fatalError("Failed to load store: \(error)")
                    }
            }
            let coordinator = container.persistentStoreCoordinator
            let store = coordinator.persistentStores[0]
            do
            {
                try coordinator.migratePersistentStore(store, to : path, options : nil, withType : NSSQLiteStoreType)
                completion(nil)
            }
            catch
            {
                completion("\(Errors.coredataBackupError)\(error.localizedDescription)")
            }
        }
0

All Articles