Docs 菜单
Docs 主页
/ /
Atlas Device SDKs
/ /

使用 SwiftUI 处理同步错误 - Swift SDK

在此页面上

  • 处理同步错误

在开发使用 Device Sync 的应用程序时,应设置错误处理程序。 此错误处理程序将检测并响应任何失败的同步相关 API 调用。

提示

另请参阅:

For 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.

对于同步错误处理程序的 SwiftUI 友好实施,请创建一个带有可选@Published变量的 ObservableObject ,以包含潜在的错误。 此处理程序使用SyncManager侦听错误。 SyncManager报告SyncError类型的错误,并且还报告其他连接问题。

有关更多信息,请参阅底层 Objective-C RLMSyncError。

final class ErrorHandler: ObservableObject {
@Published 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
}
}
}
}

提示

有关常见 错误的列表以及如何处理这些错误,请参阅Device Sync Atlas App ServicesDevice Sync文档中的 同步错误 。

将错误处理程序初始化为@StateObject 。将其作为环境对象注入到视图层次结构中。在此示例中,当发生同步错误时,我们会向用户显示.alert

let app = App(id: flexibleSyncAppId)
@main
struct realmSwiftUIApp: SwiftUI.App {
// Initialize the error handler
@StateObject 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 ?? "")
}
}
}
}

然后,在观察 Realm App的视图中,您可以使用错误处理程序作为@EnvironmentObject来响应同步错误。此处发生的错误会使用上面视图中设置的.alert向用户弹出警报。

struct NextView: View {
@ObservedObject var app: RealmSwift.App
// Use the error handler that you injected into the environment
@EnvironmentObject var errorHandler: ErrorHandler
var body: some View {
Text("You might log users in or handle errors in this view")
}
}

后退

筛选数据

来年

在后台同步数据

在此页面上