Manejar errores de sincronización
While developing an application that uses Device Sync, you should set an error handler. This error handler will detect and respond to any failed sync-related API calls.
Tip
Para obtener una aplicación de ejemplo completa con una implementación de controlador de errores de sincronización funcional,
Cree una aplicación de plantilla y revise el cliente SwiftUI. La implementación del controlador de errores se encuentra en el App.swift archivo.
Para una implementación compatible con SwiftUI de un controlador de errores de sincronización, cree un ObservableObject Con una @Published variable opcional para contener un posible error. Este controlador usa SyncManager para detectar errores. El SyncManager informa errores del tipo SyncError y también otros problemas de conexión.
Para obtener más información, consulte el Objective-C RLMSyncError subyacente.
final class ErrorHandler: ObservableObject { var error: Swift.Error? init(app: RealmSwift.App) { // Sync Manager listens for sync errors. app.syncManager.errorHandler = { error, syncSession in if let error = error as? SyncError { /* Handle specific SyncError cases, or use a switch * statement to handle all Sync error codes. * In this case, ignore a .connectionFailed error and * continue executing the app code. */ if error.code == .connectionFailed { return } self.error = error } else if let error = error as? POSIXError { /* The error handler may also report NSError types to * allow for error handling in a platform-idiomatic way. * In this case, handle a connection timeout error as * an .ETIMEDOUT error in the POSIXError domain. */ if error.code == .ETIMEDOUT { return } self.error = error } } } }
Tip
For a list of common Device Sync errors and how to handle them, refer to Sync Errors in the App Services Device Sync documentation.
Inicialice el manejador de errores como un @StateObject. Inyéctelo en la jerarquía de vistas como un objeto de entorno. En este ejemplo, mostramos un .alert al usuario cuando ocurre un error de sincronización.
let app = App(id: flexibleSyncAppId) @main struct realmSwiftUIApp: SwiftUI.App { // Initialize the error handler var errorHandler = ErrorHandler(app: app) var body: some Scene { WindowGroup { NextView(app: app) // Inject the error handler as an environment object .environmentObject(errorHandler) // Display an alert to the user containing the error when a Sync error occurs .alert(Text("Error"), isPresented: .constant(errorHandler.error != nil)) { Button("OK", role: .cancel) { errorHandler.error = nil } } message: { Text(errorHandler.error?.localizedDescription ?? "") } } } }
Then, in the view where you are observing the Realm App, you can use the error handler as an @EnvironmentObject to react to Sync errors. An error that occurs here pops up an alert for the user, using the .alert set in the view above.
struct NextView: View { var app: RealmSwift.App // Use the error handler that you injected into the environment var errorHandler: ErrorHandler var body: some View { Text("You might log users in or handle errors in this view") } }