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.
TipFor a complete example app with a working Sync error handler implementation, create a template app and check out the SwiftUI client. The error handler implementation is in the App.swift
file.
For a SwiftUI-friendly implementation of a Sync error handler, create an ObservableObject
with an optional @Published
variable to contain a potential error. This handler uses the SyncManager to listen for errors. The SyncManager
reports errors of the type SyncError
, and it also reports other connection issues.
For more information, refer to the underlying Objective-C RLMSyncError.
final class ErrorHandler: ObservableObject { @Published var error: Swift.Error? init(app: RealmSwift.App) { app.syncManager.errorHandler = { error, syncSession in if let error = error as? SyncError { if error.code == .connectionFailed { return } self.error = error } else if let error = error as? POSIXError { 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.
Initialize the error handler as a @StateObject
. Inject it into the view hierarchy as an environment object. In this example, we display an .alert
to the user when a Sync error occurs.
let app = App(id: flexibleSyncAppId)@mainstruct realmSwiftUIApp: SwiftUI.App { @StateObject var errorHandler = ErrorHandler(app: app) var body: some Scene { WindowGroup { NextView(app: app) .environmentObject(errorHandler) .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 { @ObservedObject var app: RealmSwift.App @EnvironmentObject var errorHandler: ErrorHandler var body: some View { Text("You might log users in or handle errors in this view") }}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4