How can I display a popup message in Swift that disappears after 3 seconds or can be cancelled by user immediatelly?
You can use an NSTimer
to decrement a counter, update the alert view and dismiss the alert view when the counter reaches 0. This code is adapted from my Objective-C answer
class ViewController: UIViewController {
var alertController: UIAlertController?
var alertTimer: NSTimer?
var remainingTime = 0
var baseMessage: String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.showAlertMsg("Test Alert", message: "This will disappear in ", time: 5)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showAlertMsg(title: String, message: String, time: Int) {
guard (self.alertController == nil) else {
print("Alert already displayed")
return
}
self.baseMessage = message
self.remainingTime = time
self.alertController = UIAlertController(title: title, message: self.alertMessage(), preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
print("Alert was cancelled")
self.alertController=nil;
self.alertTimer?.invalidate()
self.alertTimer=nil
}
self.alertController!.addAction(cancelAction)
self.alertTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.countDown), userInfo: nil, repeats: true)
self.presentViewController(self.alertController!, animated: true, completion: nil)
}
func countDown() {
self.remainingTime -= 1
if (self.remainingTime < 0) {
self.alertTimer?.invalidate()
self.alertTimer = nil
self.alertController!.dismissViewControllerAnimated(true, completion: {
self.alertController = nil
})
} else {
self.alertController!.message = self.alertMessage()
}
}
func alertMessage() -> String {
var message=""
if let baseMessage=self.baseMessage {
message=baseMessage+" "
}
return(message+"\(self.remainingTime)")
}
}
Related videos on Youtube
user3766930
Updated on October 09, 2022Comments
-
user3766930 over 1 year
In my swift app I have a UIViewController with a single button.
This button invokes a function that calls a popup that disappears after 3 seconds. Also, after that time it prints a message to the console. The code of this function is as follows:
func showAlertMsg(title: String, message: String){ let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) self.presentViewController(alertController, animated: true, completion: nil) let delay = 3.0 * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue(), { alertController.dismissViewControllerAnimated(true, completion: nil) print("popup disappeared") }) }
That works fine, but I wanted to introduce some improvement. I wanted to add there a button that will cancel this popup immediately and then avoid displaying the message in the console. Is there a way of displaying such popup to the user? Also - is there a way of showing in this popup message the counter with number of seconds running out that shows how much time is left until the popup disappears?
-
Paulw11 about 8 yearsHere is a similar answer I wrote in Objectice C stackoverflow.com/questions/36048240/…. Essentially you need to use an NSTimer to count down and dismiss the alert after the required time
-
-
user3766930 about 8 yearsHey @DanL, thanks, SCLAlertView looks interesting! However - is there any way of showing the counter of how many seconds left until the popup closes?
-
Dan Levy about 8 yearsI don't think what it's built into SCLAlertView, but I don't see any reason why you can't create an NSTimer to show to the user. I would look online for a countdown timer in swift if you don't know how to create one. You would then fire the timer when the SCLAlertView appears. Just be aware that, if you have the alert set for three seconds, the timer may only count down two or two and a half seconds because it takes a moment to load. I would just play around with the timer to make it work.
-
Fluidity over 7 yearsHere is a link to the updated Swift 3 code: gist.github.com/anonymous/aadd8e56f2049062c68458c477c28a34