Source code for the WriteFreely SwiftUI app for iOS, iPadOS, and macOS
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

43 linhas
1.2 KiB

  1. // Based on https://www.ralfebert.com/swiftui/generic-error-handling/
  2. import SwiftUI
  3. struct ErrorAlert: Identifiable {
  4. var id = UUID()
  5. var message: String
  6. var dismissAction: (() -> Void)?
  7. }
  8. class ErrorHandling: ObservableObject {
  9. @Published var currentAlert: ErrorAlert?
  10. func handle(error: Error) {
  11. currentAlert = ErrorAlert(message: error.localizedDescription)
  12. }
  13. }
  14. struct HandleErrorByShowingAlertViewModifier: ViewModifier {
  15. @StateObject var errorHandling = ErrorHandling()
  16. func body(content: Content) -> some View {
  17. content
  18. .environmentObject(errorHandling)
  19. .background(
  20. EmptyView()
  21. .alert(item: $errorHandling.currentAlert) { currentAlert in
  22. Alert(title: Text("Error"),
  23. message: Text(currentAlert.message),
  24. dismissButton: .default(Text("OK")) {
  25. currentAlert.dismissAction?()
  26. })
  27. }
  28. )
  29. }
  30. }
  31. extension View {
  32. func withErrorHandling() -> some View {
  33. modifier(HandleErrorByShowingAlertViewModifier())
  34. }
  35. }