Search code examples
iosswifttimercountdownone-time-password

How to give count down for OTP in Swift


I need to give 60 sec time countdown for resend otp. and if i click verifyOtp butn then count down to be stop. and i want that otp to be expaire. in count down time resend otpbutton to be disable.. please suggest me how to set count down for resendotp.

i am getting otp in registrService().

    do{
                var json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
                let regUserStatus = json["status"] as? String

                if regUserStatus == "sucess"
                {
                    print("the json regggggggggggis \(json)")
                    let phNum = json["mobile_number"] as? Int
                    let status = json["status"] as? String
                    self.otpField = json["otp"] as? Int
                }
                else{
                    DispatchQueue.main.async {
                        self.registerButton.isHidden = false
                        self.sendOtpButton.isHidden = true
                        self.otpTextField.isHidden = true
                        self.resendButn.isHidden = true
                        self.otpcountLabel.isHidden = true
                        AlertFun.ShowAlert(title: "", message: "user exist", in: self)
                    }

                }
            }

resendButton .

   @IBAction func resendOtpButn(_ sender: Any) {
    print("resendotp tapped")

    registerService()
   }

Solution

  • After you have started the OTP process you need to create a 60 seconds timer that when it expires it runs a selector method:

    create a class level Timer property:

    var otpTimer: Timer?
    

    create the timer when your reg button is clicked

    @IBAction func regButn(_ sender: Any) {
      registerService()
      startTimer()
    }
    
    func startTimer() {
      optTimer?.invalidate(). //cancels it if already running
      optTimer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(timerDidFire(_:)), userInfo: userInfo, repeats: false)
    }
    

    When your timer hits zero the selector will be called, and you can do whatever you want to do to expire the otp request

    @objc func timerDidFire(_ timer: Timer) {
    
       // timer has completed.  Do whatever you want...
    }
    

    if the resend button is tapped, I think you want to restart the timer, so ...

    @IBAction func resendOtpButn(_ sender: Any) {
      registerService()
      startTimer()
    }
    

    You will probably also want to cancel the timer if your otp completes successfully, so in your success completion handler you can just do

    self.optTimer?.invalidate()