Created
November 29, 2016 03:22
-
-
Save anonymous/aadd8e56f2049062c68458c477c28a34 to your computer and use it in GitHub Desktop.
Swift 3 and iOS UIMessageAlert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Put these in your UIViewController subclass: | |
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.baseMessage, 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 = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.countDown), userInfo: nil, repeats: true) | |
self.present(self.alertController!, animated: true, completion: nil) | |
} | |
func countDown() { | |
self.remainingTime -= 1 | |
if (self.remainingTime < 0) { | |
self.alertTimer?.invalidate() | |
self.alertTimer = nil | |
self.alertController!.dismiss(animated: 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)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment