UIAlertController does not show when a var reaches a certain value - ios

I'd like to get an alert to show when 3 specific value is reached,
here's my code
func SectionAlert () {
if (section1score >= 10){
let alertController: UIAlertController = UIAlertController(title: "Alert", message: "\((section1score as NSNumber).stringValue)", preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) {
action -> Void in
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion: nil)
} else if (section2score >= 10){
} else if (section3score >= 10){
}
}
My App updates each sections value when a cell is tapped in the TableView
My code does not show any error but it does not give me my alert when my value reaches 10 and over
any ideas??
thanks !

Related

How to show alert after keyboard has been shown in UITextView textViewDidBeginEditing

Inside textViewDidBeginEditing I'm showing alert using UIAlertController. Alert is shown prior to the keyboard (on simulator).
How do I show keyboard before alert pops up?
func textViewDidBeginEditing(_ textView: UITextView) {
if self.balance <= 0 {
let alert = UIAlertController(title: "Balance Low", message: "Your balance is low.", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (cancel) in
}
let okAction = UIAlertAction(title: "Buy", style: UIAlertActionStyle.default) { (action) in
self.segueToBuy()
}
alert.addAction(cancelAction)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
}
Please use DispatchQueue.main.asyncAfter to show the alert after certain delay, whenever user typed the text in UITextView.
func asyncAfter(deadline: DispatchTime, qos: DispatchQoS = default, flags: DispatchWorkItemFlags = default, execute work: #escaping #convention(block) () -> Void)
Delcare private instance variable which is used to show alert, locally.
var showAlert = true
Try the code shown below in textViewDidBeginEditing:
func textViewDidBeginEditing(_ textView: UITextView) {
if self.showAlert && self.balance <= 0 {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
textView.endEditing(true)
let alert = UIAlertController(title: "Balance Low", message: "Your balance is low.", preferredStyle: UIAlertController.Style.alert)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel) { (cancel) in
self.showAlert = false
textView.becomeFirstResponder()
}
let okAction = UIAlertAction(title: "Buy", style: UIAlertAction.Style.default) { (action) in
textView.endEditing(true)
self.segueToBuy()
}
alert.addAction(cancelAction)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
}
}

Checking the value in textfield before alert controller hides - iOS swift

What I am trying to do is that I am taking user's contact number (mobile number) if it is correct then it should continue the signup otherwise the alert controller should not hide and show some error
let alertController = UIAlertController(title: "Phone Number", message: "Please enter your number", preferredStyle: .alert)
alertController.addTextField {
(textField) -> Void in
textField.tag = 128
textField.delegate = self
textField.placeholder = "923xxxxxxxxx"
}
alertController.addAction(UIAlertAction(title: "Continue", style: .default, handler: {
alert -> Void in
let textField = alertController.textFields![0] as UITextField
if (textField.text?.count)! == 12 && ((textField.text?.substring(to: 3))!) == "923" {
//my code
}
else {
//should show/keep alert controler
}
}))
self.present(alertController, animated: true, completion: nil)
Try out this,
let alertController = UIAlertController(title: "Phone Number", message: "Please enter your number", preferredStyle: .alert)
alertController.addTextField {
(textField) -> Void in
textField.tag = 128
textField.delegate = self
textField.placeholder = "923xxxxxxxxx"
}
alertController.addAction(UIAlertAction(title: "Continue", style: .default, handler: {
alert -> Void in
let textField = alertController.textFields![0] as UITextField
if (textField.text?.count)! == 12 && ((textField.text?.substring(to: 3))!) == "923"
{
//my code
}
else
{
//alert with error
let alertControllerError = UIAlertController(title: "error", message: "error here", preferredStyle: .alert)
alertControllerError.addAction(UIAlertAction(title: "ok", style: .default, handler: { alert -> Void in
}))
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) {
self.present(alertControllerError, animated: true, completion: nil)
}
}
}))
self.present(alertController, animated: true, completion: nil)
You could disable the button (UIAlertAction) by default. Then listen to text changes in your UITextField and update the button accordingly:
var autoEnableAlertAction: UIAlertAction?
func presentAlertController() {
// alert controller
let ac = UIAlertController(title: "Registration", message: "Please enter your phone number.", preferredStyle: .Alert)
// alert action - disabled by default
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
okAction.enabled = false
ac.addAction(okAction)
// store a reference to the alert action to enable / disable it later
autoEnableAlertAction = okAction
ac.addTextFieldWithConfigurationHandler { tf in
// listen for changes in the textfield
tf.addTarget(self, action: #selector(self.checkTextFieldText(_:)), forControlEvents: .EditingChanged)
}
presentViewController(ac, animated: true, completion: nil)
}
#objc func checkTextFieldText(textField: UITextField) {
autoEnableAlertAction?.enabled = textField.text?.characters.count >= 5
}
Sorry for my answer being a Swift 2 version... :)
func presentAlertController()
{
let alertController = UIAlertController(title: "Phone Number", message: "Please enter your number", preferredStyle: .alert)
alertController.addTextField {
(textField) -> Void in
textField.tag = 128
textField.placeholder = "923xxxxxxxxx"
}
alertController.addAction(UIAlertAction(title: "Continue", style: .default, handler: {
alert -> Void in
let textField = alertController.textFields![0] as UITextField
if (textField.text?.count)! == 12 && textField.text?.prefix(3) == "923"
{
print("sucess")
}
else
{
print("Incorrect Number")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(2)) {
self.presentAlertController(parameters: parameters)
}
}
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:{
alert -> Void in
}))
self.present(alertController, animated: true, completion: nil)
}

Swift: How to make an action occur if UIAlertAction is pressed?

I'm trying to make an app where if the score is 3 the app displays a message that says "you lose" but keeps '3' as the number in the score label until the End Game option in the popup is pressed, at which point the score goes back to 0 for a new game. I am new to swift and am having difficulty and would really appreciate any and all help! I am not sure if making an IBAction for the alert action is the right thing to do or not.
else if rightscorecount == 3 {
let alert = UIAlertController(title: "Game", message: "You Lose!", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "End Game", style: UIAlertActionStyle.default) { UIAlertAction in})
self.present(alert, animated: true, completion: nil)
}
}
#IBAction func test(sender: UIAlertAction) {
rightscorecount = 0
rightscorelabel.text = String(rightscorecount)
}
Try this:
let alertController = UIAlertController.init(title: "Game", message: "You Lose!", preferredStyle: .alert)
alertController.addAction(UIAlertAction.init(title: "End Game", style: .default, handler: { (action) in
// Your handler goes here
self.someFunction()
}))
self.present(alertController, animated: true) {
// Completion block
}
And your function
func someFunction() {
// Function body goes here
}

UIAlertController not appearing

I have an alert controller that is supposed to appear after a user enters an incorrect amount of characters in the text fields. The alert controller does not appear at all. W
func usernameFieldCharacters() {
let alertController = UIAlertController(title: "Alert", message: "Five characters or more is required in all fields" , preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: .Default) {
action -> Void in // Does not do anything
}
alertController.addAction(okAction) // adds the OK button to
// to alert controller
let allowedChars = 5 // character amount has to be equal or greater in each field
let usernameCount = theUsernameField.text?.characters.count
if usernameCount < allowedChars {
self.presentViewController(alertController, animated: true, completion: nil)
} else {
alertController.viewDidAppear(false)
}
}
the code works correct, when u move the alertcontroller to i.e. viewDidAppear-method:
class ViewController: UIViewController {
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let allowedChars = 5 // character amount has to be equal or greater in each field
let usernameCount = theUsernameField.text?.characters.count
if usernameCount < allowedChars {
// Do any additional setup after loading the view, typically from a nib.
let alertController = UIAlertController(title: "Alert", message: "Five characters or more is required in all fields" , preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: .Default) {
action -> Void in // Does not do anything
}
alertController.addAction(okAction) // adds the OK button to
// to alert controller
self.present(alertController, animated: true, completion: nil)
}
Above code works correctly.
And alertController.viewDidAppear(false) is needn't

UialertController to show only once when the var hits an certain Value

so the way my app works is you tap on a cell , a var value gets modified (+1 for example). I've figured out how to get a UIalert to pop when my var reaches a certain value (10). But now everytime I update the var the alert pops. What i would like it to do is to pop when the var hits 10 and stop after that
Heres the code :
if (section1score >= 10){
let alertController: UIAlertController = UIAlertController(title: NSLocalizedString("Section 1 score is over 10", comment: ""),
message: " \(message1)",
preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) {
action -> Void in }
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
if (section2score >= 10){
let alertController: UIAlertController = UIAlertController(title: NSLocalizedString("Section 2 Score is over 10", comment: ""),
message: "\(message2)",
preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) {
action -> Void in }
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
Setup a Bool to check if the alert has been shown or not. Create the Bool globally and set it to false initially.
var showedAlert = false
func yourFunction() {
if section1score >= 10 && showedAlert == false {
// show alert
showedAlert = true
}
if section2score >= 10 && showedAlert == false {
// show alert
showedAlert = true
}
}
Comparison Operators
You could use a property to keep track of when you show the alert so that once you show it, you won't show it again.
var hasShownAlert: Bool = false
if (section1score >= 10 && !hasShownAlert){
let alertController: UIAlertController = UIAlertController(title: NSLocalizedString("Section 1 score is over 10", comment: ""),
message: " \(message1)",
preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) {
action -> Void in }
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion: nil)
hasShownAlert = true
}
if (section2score >= 10 && !hasShownAlert){
let alertController: UIAlertController = UIAlertController(title: NSLocalizedString("Section 2 Score is over 10", comment: ""),
message: "\(message2)",
preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) {
action -> Void in }
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion: nil)
hasShownAlert = true
}

Resources