How sync to CloudKit with json file based storage - macOS SwiftUI app

133 views Asked by At

I persist the app data using a Json file, how can I add sync with apple cloud services?

Here is a snipet from the store code:

@MainActor
final class Store: ObservableObject {
    @Published var storeData: StoreData =  StoreData()
    
    private static func fileURL() throws -> URL {
        /// You use the shared instance of the FileManager class to get the location of the Documents directory for the current user.
        try FileManager.default.url(for: .documentDirectory,
                                    in: .userDomainMask,
                                    appropriateFor: nil,
                                    create: false)
        .appendingPathComponent("store.data") /// Call appendingPathComponent(_:) to return the URL of a file named store.data.
    }
    
    func resetData(){
        storeData = StoreData()
    }
    
    static func load() async throws -> StoreData {
        /// Calling withCheckedThrowingContinuation suspends the load function,
        /// then passes a continuation into a closure that you provide.
        /// A continuation is a value that represents the code after an awaited function
        try await withCheckedThrowingContinuation{ continuation in
            load{ result in
                ///In the completion handler, you must call one of the continuation’s resume methods exactly once on every execution path.
                switch result {
                case .failure(let error):
                    continuation.resume(throwing: error) /// Continuations have methods for returning a value, returning a Result, and throwing an error.
                case .success(let data):
                    continuation.resume(returning: data)
                }
            }
        }
    }
    

    
    @discardableResult // The save function returns a value that callers of the function may not use. The @discardableResult attribute disables warnings about the unused return value.
    static func save(data: StoreData) async throws -> Bool {
        try await withCheckedThrowingContinuation { continuation in
            save(storeData: data) { result in
                switch result {
                case .failure(let error):
                    continuation.resume(throwing: error)
                case .success(let isSuccessfull):
                    continuation.resume(returning: isSuccessfull)
                }
            }
        }
    }
}

In the App instance I load the store on appear:

.task { // load data before the dashboard appears
                    await loadStoreData()
                }

Note: The stage I'm in its complicated to refactor to SwiftData or CodeData.

0

There are 0 answers