Как дать некоторое время (60 секунд) для повторной отправки кнопки OTP в swift - PullRequest
0 голосов
/ 19 октября 2019

У меня есть экран регистрации с проверкой OTP. Как только я коснусь regstrButton, OTP будет отправлен на зарегистрированный номер мобильного телефона. В это время кнопка повторной отправки OTP будет показывать время через 60 секунд после 60 секунд, если я нажму кнопку «Отправить повторно», тогда мне нужночтобы повторно отправить OTP, чтобы зарегистрировать номер .. как показано ниже изображения

enter image description here

кнопка повторной отправки должна показывать 60 секунд времени после этого времени мне нужно повторно отправить OTP Как?

enter image description here

мой код для службы otp:

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()
}
}

, пожалуйста, помогите мне в коде.

1 Ответ

1 голос
/ 20 октября 2019
var count = 60  // 60sec if you want
var resendTimer = Timer()

на вашей кнопке отправки

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

затем функция таймера

@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()
    }
}
...