UIAlertController.swift 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //
  2. // UIAlertController.swift
  3. // Mastodon
  4. //
  5. import UIKit
  6. import MastodonSDK
  7. // Reference:
  8. // https://nshipster.com/swift-foundation-error-protocols/
  9. extension UIAlertController {
  10. convenience init(
  11. for error: Error,
  12. title: String?,
  13. preferredStyle: UIAlertController.Style
  14. ) {
  15. let _title: String
  16. let message: String?
  17. if let error = error as? LocalizedError {
  18. var messages: [String?] = []
  19. if let title = title {
  20. _title = title
  21. messages.append(error.errorDescription)
  22. } else {
  23. _title = error.errorDescription ?? "Error"
  24. }
  25. messages.append(contentsOf: [
  26. error.failureReason,
  27. error.recoverySuggestion
  28. ])
  29. message = messages
  30. .compactMap { $0 }
  31. .joined(separator: " ")
  32. } else {
  33. _title = "Internal Error"
  34. message = error.localizedDescription
  35. }
  36. self.init(
  37. title: _title,
  38. message: message,
  39. preferredStyle: preferredStyle
  40. )
  41. }
  42. }