Ad

How To Limit Button Clicked By Time Passed Swift

I need a button where the user clicks to let everyone know they are attending a location, but I only want it to be able to be clicked up to 3 times per 24hrs depending on the contents of the button, as there is a tableView with one button per cell

I haven't tried anything as I have never used time in swift still new to it

@IBAction func myButtonClicked(_ sender: Any) {
    DataService.ds.REF_BARS.child(imageTitleLabel.text!).child("GoingCount").observeSingleEvent(of: .value, with: { (snapshot) in
        print(snapshot.value as! String)
        self.countString = snapshot.value as! String
        self.countInt = Int(self.countString)! + 1
        DataService.ds.REF_BARS.child(self.imageTitleLabel.text!).updateChildValues(["GoingCount": String(self.countInt)])
    })
}

if you can add the pre or post condition of user clicks in or around that button

Ad

Answer

You can do this for 1 button

if let storedDate = UserDefaults.standard.object(forKey:"StoredDate") as? Date {

      let toDate = Calendar.current.date(byAdding: .day, value:1, to:storedDate)
      let cliks = UserDefaults.standard.integer(forKey:"NumOfClicks")

      if Date() <= toDate { 
          if cliks < 3 {
                // do what you need and increase NumOfClicks by 1
          }
          else {
             // no more clicks this day
          }
      }
      else { 
         // date exceed may be reset the date and cliks to 1
      }
}
else {
     // first attempt 
     UserDefaults.standard.set(Date(),forKey:"StoredDate")
     UserDefaults.standard.set(1,forKey:"NumOfClicks")
     // do what you need once from here 
}

For an array handling you can think of every key above as an array instead , in storing/retrieve like [Date]/[Int]

Ad
source: stackoverflow.com
Ad