Search code examples
jsonswifttimeuibuttonone-time-password

How to give some time(60 sec) for resend OTP Button in swift


I have registration screen with OTP verification.. once i tap regstrButton then OTP will be sent to registered mobile number.. at that time resend otp button will show time 60 sec after 60 sec if i tap resend otp button then i need to resend otp to to register number.. like below images

enter image description here

resend button need to show 60 sec time after that time i need to resend otp How?

enter image description here

my code for otp service:

import UIKit
class RegistrationViewController: UIViewController, UITextFieldDelegate 
 {
//MARK:- Outlets
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var phoneNumTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var conformPasswordTextField: UITextField!
@IBOutlet weak var otpTextField: UITextField!
@IBOutlet weak var registerButton: UIButton!
@IBOutlet weak var sendOtpButton: UIButton!
@IBOutlet weak var otpcountLabel: UILabel!
@IBOutlet weak var resendButn: UIButton!

var otpField: Int?
var otpTimer = Timer()
var totalTime = 10

override func viewDidLoad() {
    super.viewDidLoad()
    self.phoneNumTextField.keyboardType = .phonePad
    otpTextField.isHidden = true
    resendButn.isHidden = true
}
  @IBAction func registerButton(_ sender: Any) {
    if (nameTextField.text ==  "" || phoneNumTextField.text == "" || passwordTextField.text ==  "" || conformPasswordTextField.text == "")
    {
        registerButton.isHidden = false
        sendOtpButton.isHidden = true
        AlertFun.ShowAlert(title: "Title", message: "RequiredAllFields", in: self)
    }
    else{
        registerButton.isHidden = true
        sendOtpButton.isHidden = false
        otpTextField.isHidden = false
        resendButn.isHidden = false
        DispatchQueue.main.async {
            self.otpTextField.text = self.otpField as? String
        }
        registerService()
        otpTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(update), userInfo: nil, repeats: true)
    }
}

@IBAction func sendOTPButton(_ sender: Any) {
    otpService()
}
@IBAction func resendOtpButn(_ sender: Any) {
    print("resendotp tapped")
    otpTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(update), userInfo: nil, repeats: true)
    registerService()
}
@objc func update() {
    if(totalTime > 0) {
        totalTime = totalTime - 1
        print(totalTime)
        otpcountLabel.text = String(totalTime)
        //resendButn.setTitle("\(totalTime) Resend Otp", for: .normal)
    }
    else {
        //otpcountLabel.isHidden = true
        otpTimer.invalidate()
        print("call your api")
        //registerService()
    }
}

//MARK:- Service part
@objc func registerService(){

    print("register tapped")

    let parameters = ["mobile_number": Int(phoneNumTextField.text ?? "") as Any,
                      "email":emailTextField.text as Any,
                      "password":passwordTextField.text as Any,
                      "name": nameTextField.text as Any]

    let url = URL(string: "https://dev.com/webservices/register")
    var req =  URLRequest(url: url!)
    req.httpMethod = "POST"
    req.addValue("application/json", forHTTPHeaderField: "Contet-Type")
    req.addValue("application/json", forHTTPHeaderField: "Accept")

    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else {return}
    req.httpBody = httpBody

    let session = URLSession.shared

    session.dataTask(with: req, completionHandler: {(data, response, error) in
        if response != nil {
            // print(response)
        }
        if let data = data {
            do{
                let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
                print("the json regggggggggggis \(json)")
                self.otpField = json["otp"] as? Int
            }catch{
                print("error")
            }
        }
    }).resume()
}
@objc func otpService(){

    let parameters = ["mobile_number": phoneNumTextField.text as Any,
                      "otp": otpTextField.text as Any]
    let url = URL(string: "https://dev.com/webservices//otpverify")
    var req =  URLRequest(url: url!)
    req.httpMethod = "POST"
    req.addValue("application/json", forHTTPHeaderField: "Contet-Type")
    req.addValue("application/json", forHTTPHeaderField: "Accept")

    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else {return}
    req.httpBody = httpBody
    let session = URLSession.shared
    session.dataTask(with: req, completionHandler: {(data, response, error) in
        if response != nil {
            // print(response)
        }
        if let data = data {

            do{
                let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
                print("the json of otppppppppp \(json)")
                DispatchQueue.main.async {
                    if (self.otpTextField.text == String(self.otpField!)){
                        print("registration successfullllll...")
                        let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
                        self.present(loginVC, animated: true)
                    }
                    else if self.otpTextField.text == ""{
                        AlertFun.ShowAlert(title: "", message: "Please enter OTP", in: self)
                        print("register fail")
                    }
                    else {
                        AlertFun.ShowAlert(title: "", message: "Invalid OTP", in: self)
                        print("register fail")
                    }
                }
            }catch{
                print("error")
            }
        }
    }).resume()
}
}

please help me in the code.


Solution

  • var count = 60  // 60sec if you want
    var resendTimer = Timer()
    

    on your submit Button

    @IBAction func sendOTPButton(_ sender: Any) {
         resendTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(update), userInfo: nil, repeats: true)
     }
    

    then timer func

    @objc func update() {
        if(count > 0) {
            count = count - 1
            print(count)
            btn.setTitle("\(count) Resend Otp", for: .normal)
        }
        else {
            resendTimer.invalidate()
            print("call your api")
            // if you want to reset the time make count = 60 and resendTime.fire()
        }
    }