Search code examples
iosswift

How can I handle the multiple click action to single button for API calling and get the true response from API


I just want to know the method to handle multiple click event on single button. (e.g. FACEBOOK like button if I tapped multiple time then it may work perfectly.)

Below code give you some idea and if there is any appropriate solution then give me as soon as possible.

class LikeViewController: UIViewController {

    //MARK:- Outlets
    @IBOutlet weak var btnLike: UIButton!
    @IBOutlet weak var lblDescription: UILabel!
    
    //MARK:- Variables
    var objModelWatchList:WatchListModel?
    var objUser = WatchListModel()
    
    //MARK:- Lifecycle methods
    override func viewDidLoad() {
        super.viewDidLoad()
        getWatchList()
        
    }

    //MARK:- Functions
    
    //Function for prepare UI
    func prepareUI() {
        btnLike.isSelected = isLike()
    }
    
    //Function for prepare data from api
    func getWatchList() {
        objUser.videoId = 216
        objUser.type = "VIDEO"
        APIService.sharedInstance.getWatchList(parameters: objUser.toDictionary() as [String : AnyObject], success: { (dataSuccess) -> (Void) in
            self.objModelWatchList = dataSuccess
            DispatchQueue.main.async {
                self.prepareUI()
                self.lblDescription.text = self.objModelWatchList?.message
            }
        }) { (resultFailure) -> (Void) in
            print(resultFailure)
        }
    }
    
    
    //Function to varify the status of like
    func isLike() -> Bool {
        return objModelWatchList!.status == 1 ? true : false
    }
    
    //MARK:- Actions
    @IBAction func btnLikeClicked(_ sender: UIButton) {
                sender.isSelected = !sender.isSelected
                self.getWatchList()
    }
}

Solution

  • The way to achieve this is to use a debouncer. Make the delay to be like 1 second, so if the user is tapping on the button multiple times before 1 second, it will cancel the previous action. So, you only need to locally update the button like/dislike state, and only call the API when the user stopped tapping.