2023-07-02 10:51:50 +00:00
|
|
|
import SwiftUI
|
|
|
|
|
|
|
|
// https://www.ralfebert.com/swiftui/generic-error-handling/
|
|
|
|
|
|
|
|
private struct ErrorAlert: Identifiable {
|
|
|
|
let id = UUID()
|
|
|
|
|
|
|
|
let title: String?
|
|
|
|
|
|
|
|
let message: String
|
|
|
|
|
|
|
|
let dismissAction: (() -> Void)?
|
|
|
|
}
|
|
|
|
|
|
|
|
@MainActor
|
|
|
|
final class ErrorHandler: ObservableObject {
|
|
|
|
static let shared = ErrorHandler()
|
|
|
|
|
2023-07-03 14:41:49 +00:00
|
|
|
@Published fileprivate var isPresented = false
|
|
|
|
|
2023-07-02 10:51:50 +00:00
|
|
|
@Published fileprivate var currentAlert: ErrorAlert?
|
|
|
|
|
|
|
|
func handle(_ error: Error, title: String? = nil, onDismiss: (() -> Void)? = nil) {
|
|
|
|
currentAlert = ErrorAlert(
|
|
|
|
title: title,
|
|
|
|
message: AppError(error).localizedDescription,
|
|
|
|
dismissAction: onDismiss
|
|
|
|
)
|
2023-07-03 14:41:49 +00:00
|
|
|
isPresented = true
|
2023-07-02 10:51:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func handle(title: String, message: String, onDismiss: (() -> Void)? = nil) {
|
|
|
|
currentAlert = ErrorAlert(
|
|
|
|
title: title,
|
|
|
|
message: message,
|
|
|
|
dismissAction: onDismiss
|
|
|
|
)
|
2023-07-03 14:41:49 +00:00
|
|
|
isPresented = true
|
2023-07-02 10:51:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct HandleErrorsByShowingAlertViewModifier: ViewModifier {
|
|
|
|
@ObservedObject private var errorHandler: ErrorHandler
|
|
|
|
|
|
|
|
init() {
|
|
|
|
errorHandler = .shared
|
|
|
|
}
|
|
|
|
|
|
|
|
func body(content: Content) -> some View {
|
|
|
|
content
|
|
|
|
// Applying the alert for error handling using a background element
|
|
|
|
// is a workaround, if the alert would be applied directly,
|
|
|
|
// other .alert modifiers inside of content would not work anymore
|
|
|
|
.background(
|
|
|
|
EmptyView()
|
2023-07-03 14:41:49 +00:00
|
|
|
.alert(
|
|
|
|
errorHandler.currentAlert?.title ?? Unlocalized.appName,
|
|
|
|
isPresented: $errorHandler.isPresented,
|
|
|
|
presenting: errorHandler.currentAlert
|
|
|
|
) { alert in
|
|
|
|
Button(role: .cancel) {
|
|
|
|
alert.dismissAction?()
|
|
|
|
} label: {
|
|
|
|
Text(L10n.Global.Strings.ok)
|
|
|
|
}
|
|
|
|
} message: { alert in
|
|
|
|
Text(alert.message.withTrailingDot)
|
|
|
|
}
|
2023-07-02 10:51:50 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
extension View {
|
|
|
|
func withErrorHandler() -> some View {
|
|
|
|
modifier(HandleErrorsByShowingAlertViewModifier())
|
|
|
|
}
|
|
|
|
}
|