skip to Main Content

I need to show a popup every time when i open the app after 20 sec.

code: with this code i can show popup only when i open the app first time after 20 sec.. but i need to show the same when i close the app and open again.. how to do that? please guide me.

var timer = Timer()
override func viewDidLoad() {
    timer = Timer.scheduledTimer(timeInterval: 20.0, target: self, selector: #selector(displayAlert), userInfo: nil, repeats: false)
} 

@objc func displayAlert()
{        
    print("after 20 sec")
    showPopup()
}

2

Answers


  1. And if you use a DispatchQueue:

    DispatchQueue.main.asyncAfter(deadline: .now() + 20) {
      // Do something here..
    }
    
    Login or Signup to reply.
  2. You want to register for notification when your app becomes active…

    For example:

    override func viewDidLoad() {
        super.viewDidLoad()
        // all your normal stuff...
        
        // register to receive notification when App becomes active
        NotificationCenter.default.addObserver(self, selector: #selector(startAlertTimer), name: UIApplication.didBecomeActiveNotification, object: nil)
    }
    @objc func startAlertTimer()
    {
        print("start 20 sec timer")
        Timer.scheduledTimer(timeInterval: 20.0, target: self, selector: #selector(showPopup), userInfo: nil, repeats: false)
    }
    @objc func showPopup() {
        print("after 20 seconds, popup")
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search