Handling ‘Send Code’ Button State in Swift with Error Handling and Countdown Timer

I’m working on a login screen in my iOS app using Swift. The user needs to enter their phone number and press a “Send Code” button to receive a verification code. How can I implement the following features into my send code button?

  1. The button should be disabled and greyed out immediately after the user presses it, regardless of any errors.
  2. If there is an error (e.g., the user didn’t enter enough digits), the button should be re-enabled after the user dismisses the error alert. The countdown timer should not start in this case.
  3. If the user successfully receives a verification code, the button should remain disabled for 1 minute, during which a countdown timer is displayed.

The point of this is to prevent users from spamming the “Send Code” button. Here is the relevant code:

import UIKit
import FirebaseAuth
import FirebaseFunctions

class LoginViewController: BaseViewController, UITextFieldDelegate {

    let phoneTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "Phone number"
        textField.borderStyle = .roundedRect
        textField.keyboardType = .numberPad
        textField.translatesAutoresizingMaskIntoConstraints = false
        return textField
    }()
    
    let sendCodeButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Send code", for: .normal)
        button.layer.cornerRadius = 10
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
        button.isEnabled = false
        button.addTarget(self, action: #selector(sendCodeButtonTapped), for: .touchUpInside)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()
    
    let countdownLabel: UILabel = {
        let label = UILabel()
        label.text = ""
        label.font = UIFont.systemFont(ofSize: 14)
        label.textAlignment = .left
        label.textColor = .gray
        label.translatesAutoresizingMaskIntoConstraints = false
        label.isHidden = true
        return label
    }()
    
    lazy var functions = Functions.functions()
    var isCountdownActive = false
    var countdownEndTime: Date?

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        updateButtonStyles()
        phoneTextField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
        loadCountdownState()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        updateSendCodeButtonState()
    }

    @objc private func sendCodeButtonTapped() {
        guard let phoneNumber = phoneTextField.text, phoneNumber.count == 10 else {
            showAlert(title: "Error", message: "Phone number must be exactly 10 digits.")
            sendCodeButton.isEnabled = true
            return
        }
        
        let formattedPhoneNumber = "+1(phoneNumber)"
        
        sendCodeButton.isEnabled = false
        updateSendCodeButtonState()
        
        activityIndicator.startAnimating()
        
        functions.httpsCallable("checkPhoneNumberExists").call(["phoneNumber": formattedPhoneNumber]) { [weak self] result, error in
            self?.activityIndicator.stopAnimating()
            
            if let error = error {
                self?.showAlert(title: "Error", message: "Error checking phone number: (error.localizedDescription)")
                self?.sendCodeButton.isEnabled = true
                return
            }
            
            guard let data = result?.data as? [String: Any], let exists = data["exists"] as? Bool else {
                self?.showAlert(title: "Error", message: "Invalid response from server.")
                self?.sendCodeButton.isEnabled = true
                return
            }
            
            if exists {
                self?.sendVerificationCode(to: formattedPhoneNumber)
            } else {
                self?.showAlert(title: "Error", message: "Phone number does not exist. Please sign up first.")
                self?.sendCodeButton.isEnabled = true
            }
        }
    }

    private func sendVerificationCode(to phoneNumber: String) {
        PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { [weak self] verificationID, error in
            if let error = error {
                self?.showAlert(title: "Error", message: "Unable to send code. Please try again.")
                self?.sendCodeButton.isEnabled = true
                return
            }
            
            UserDefaults.standard.set(verificationID, forKey: "authVerificationID")
            UserDefaults.standard.set(phoneNumber, forKey: "phoneNumber")
            
            self?.countdownLabel.isHidden = false
            self?.startCountdown(seconds: 60)
            
            let verificationVC = LoginPhoneVerificationViewController(phoneNumber: phoneNumber)
            self?.navigationController?.pushViewController(verificationVC, animated: true)
        }
    }

    private func startCountdown(seconds: Int) {
        var remainingSeconds = seconds
        isCountdownActive = true
        countdownEndTime = Date().addingTimeInterval(TimeInterval(seconds))
        UserDefaults.standard.set(countdownEndTime?.timeIntervalSince1970, forKey: "countdownEndTime")
        countdownLabel.text = "Resend code in: (remainingSeconds)s"
        
        Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] timer in
            remainingSeconds -= 1
            if remainingSeconds > 0 {
                self?.countdownLabel.text = "Resend code in: (remainingSeconds)s"
            } else {
                timer.invalidate()
                self?.isCountdownActive = false
                self?.countdownEndTime = nil
                UserDefaults.standard.removeObject(forKey: "countdownEndTime")
                self?.updateSendCodeButtonState()
                self?.countdownLabel.isHidden = true
            }
     

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật