Home > Mobile >  How to show a popup after 20 sec of an app open every time in swift
How to show a popup after 20 sec of an app open every time in swift

Time:08-26

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

CodePudding user response:

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

CodePudding user response:

And if you use a DispatchQueue:

DispatchQueue.main.asyncAfter(deadline: .now()   20) {
  // Do something here..
}
  • Related