user11262882
user11262882

Reputation:

How do I make a button appear just for a limited time?

I have a UIButton: @IBAction func button1(_ sender: Any) { }. What I want is to just display it for two days after the user downloads the app, then I want it to disappear.

I created a (Countdown) timer:

var timer:Timer?
var time = 172800 //2Days

Then I created this function:

@objc func passedTime(){
    time -= 1

    if time <= 0 {
        timer!.invalidate()
        timer = nil
    }
}

In my viewDidLoad:

timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(passedTime), userInfo: nil, repeats: false)  

I obviously want the time to go on even if the user closes the app as well.

Upvotes: 0

Views: 50

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can't run a timer while the app is closed. This is what you need to do when the user opens the app:

@IBOutlet weak var button:UIButton!

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

       self.button.isHidden = true
}
else {
     let today = Date()
     let after2Days = Calendar.current.date(byAdding: .day, value: 2, to: today)
     // save
     UserDefaults.standard.set(after2Days,forKey:"storedDate")
} 

Upvotes: 2

Related Questions