Phương pháp cơ bản để hiển thị thông báo cho người dùng là bằng UIAlertController. Việc hiển thị các thông báo giống nhau trong các phần khác nhau của ứng dụng là điều thường thấy. Để tránh trùng lặp, chúng ta có thể tạo các phương thức để cấu hình cho thông báo đó.

Đây là cách khai báo một thông báo mới:

extension UIAlertController {
    static func signOutConfirmation(onConfirm: @escaping () -> Void) -> UIAlertController {
        let ok = UIAlertAction(title: "OK", style: .default) { _ in onConfirm() }
        let cancel = UIAlertAction(title: "Cancel", style: .cancel)
        
        let alert = UIAlertController(title: nil, message: "Are you sure?", preferredStyle: .alert)
        alert.addAction(ok)
        alert.addAction(cancel)
        
        return alert
    }
}

Và cách sử dụng thông báo:

let source = UIViewController()
let alert = UIAlertController.signOutConfirmation { 
    print("Signed out") 
}
source.present(alert, animated: true)

Cách tiếp cận này sử dụng đoạn mã đã soạn sẵn trước đó, sắp xếp các thông báo của bạn ở một nơi và làm cho chúng dễ đọc hơn, dễ quản lý hơn.

Cảm ơn bạn đã đón đọc!