blob: 3552b487ecbf7a481126f38fa385a8534f33f4a6 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
//
// UIAlertController+Error.swift
// MullvadVPN
//
// Created by pronebird on 11/12/2019.
// Copyright © 2019 Mullvad VPN AB. All rights reserved.
//
import Foundation
import UIKit
/// An extension for presenting `LocalizedError` subclasses in `UIAlertController`
extension UIAlertController {
convenience init<Error>(_ error: Error, preferredStyle: UIAlertController.Style)
where Error: LocalizedError
{
let title = error.errorDescription
let message = [error.failureReason, error.recoverySuggestion]
.compactMap { $0 }
.joined(separator: "\n\n")
self.init(title: title, message: message, preferredStyle: preferredStyle)
}
}
extension UIViewController {
/// Present an instance of `LocalizedError` using `UIAlertController`
/// Note: this method adds a default "OK" action when `configurationBlock` is not given
func presentError<Error>(
_ error: Error,
preferredStyle: UIAlertController.Style,
configurationBlock: ((UIAlertController) -> Void)? = nil,
completionBlock: (() -> Void)? = nil)
where Error: LocalizedError
{
let alertController = UIAlertController(error, preferredStyle: preferredStyle)
if let configurationBlock = configurationBlock {
configurationBlock(alertController)
} else {
alertController.addAction(
UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .cancel)
)
}
self.present(alertController, animated: true, completion: completionBlock)
}
}
|