AlertController is being popped every time in nested conditions swift ios

I have defined an alertcontroller when username or password is not correct the alert should pop, and it is working fine. but when the username & password is matched despite matching it pops up everytime when log in. I think I have not defined nested condition in a right way? help me to sort the multiple nested condition.

Code for Login

  • Undefined symbols for architecture armv7 when adding CocoaAsyncSocket
  • Preventing decimals with NSNumberFormatter
  • Capturing closure values in Swift
  • IOS: automatic reference counting
  • Xcode 7: Linker warning for -F/<path> but no settings in app.xcodeproj/project.pbxproj match <path>
  • Project Crashes After Rename
  • import UIKit
    import CoreData
    import Foundation
    
     class ViewController: UIViewController {
    
    var usernameGlobal : String = ""
    
    @IBOutlet weak var emailText: UITextField!
    @IBOutlet weak var passText: UITextField!
    
    @IBOutlet weak var loginButton: UIButton!
    @IBAction func loginAction(_ sender: Any) {
    
        let appDel = UIApplication.shared.delegate as! AppDelegate
        let context = appDel.persistentContainer.viewContext
    
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
            request.returnsObjectsAsFaults = false
          //  request.predicate = NSPredicate(format: "username = %@", "" + emailText.text!)
    
    
        do {
    
        let results = try! context.fetch(request)
    
            if(results.count > 0){
    
                for result in results as! [NSManagedObject]
                {
    
    
                    if  emailText.text == result.value(forKey: "username") as? String && passText.text == result.value(forKey: "password") as? String {
                        print(emailText.text!, passText.text!)
                        usernameGlobal = self.emailText.text!
                        let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle : nil)
                        let desController = mainStoryBoard.instantiateViewController(withIdentifier: "AddViewController") as! AddViewController
                        let newFrontViewController = UINavigationController.init(rootViewController:desController)
                        revealViewController().pushFrontViewController(newFrontViewController, animated: true)
    
                    }
    
                    else {
    
                           let alertController = UIAlertController(title: "Oops!", message: "Incorrect username or password", preferredStyle: .alert)
    
                            let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                            alertController.addAction(defaultAction)
    
                            present(alertController, animated: true, completion: nil)
                        }
    
                }
    
                }
            }
        }
    
    
    
    @IBAction func signupSegue(_ sender: Any) {
    
        let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle : nil)
        let desController = mainStoryBoard.instantiateViewController(withIdentifier: "SignupViewController") as! SignupViewController
        let newFrontViewController = UINavigationController.init(rootViewController:desController)
        revealViewController().pushFrontViewController(newFrontViewController, animated: true)
    
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        loginButton.backgroundColor = UIColor.blue
    
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    }
    

    2 Solutions Collect From Internet About “AlertController is being popped every time in nested conditions swift ios”

    You can use this code:

    @IBAction func loginAction(_ sender: Any) {
    
            let appDel = UIApplication.shared.delegate as! AppDelegate
            let context = appDel.persistentContainer.viewContext
            let isMatched = false
            let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
            request.returnsObjectsAsFaults = false
    
             do {
    
                let results = try! context.fetch(request)
    
                if(results.count > 0){
    
                    for result in results as! [NSManagedObject]
                    {
    
    
                        if  emailText.text == result.value(forKey: "username") as? String && passText.text == result.value(forKey: "password") as? String {
                            print(emailText.text!, passText.text!)
                            usernameGlobal = self.emailText.text!
                            let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle : nil)
                            let desController = mainStoryBoard.instantiateViewController(withIdentifier: "AddViewController") as! AddViewController
                            let newFrontViewController = UINavigationController.init(rootViewController:desController)
                            revealViewController().pushFrontViewController(newFrontViewController, animated: true)
                            isMatched = true
                            break
    
                        }
    
                    }
    
                    if !isMatched {
    
                          let alertController = UIAlertController(title: "Oops!", message: "Incorrect username or password", preferredStyle: .alert)
                          let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                          alertController.addAction(defaultAction)
    
                          present(alertController, animated: true, completion: nil)
                     }
    
                }
            }
        }
    

    Changes:

    You add

            let isMatched = false
    

    You add break statement in if condition. So that it breaks the loop once username and password is matched. Then after for loop check if the isMatched is false, then show the result.

    if your result contains multiple different element then else block will execute multiple time. thats why alert appeared multiple time . when you found a match then you should return . if no match found then after loop alert will appear for one time .

    Use this:

           @IBAction func loginAction(_ sender: Any) {
    
                let appDel = UIApplication.shared.delegate as! AppDelegate
                let context = appDel.persistentContainer.viewContext
    
                let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
                request.returnsObjectsAsFaults = false
                //  request.predicate = NSPredicate(format: "username = %@", "" + emailText.text!)
    
    
                do {
    
                    let results = try! context.fetch(request)
    
                    if(results.count > 0){
    
                        for result in results as! [NSManagedObject]
                        {
    
    
                            if  emailText.text == result.value(forKey: "username") as? String && passText.text == result.value(forKey: "password") as? String {
                                print(emailText.text!, passText.text!)
                                usernameGlobal = self.emailText.text!
                                let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle : nil)
                                let desController = mainStoryBoard.instantiateViewController(withIdentifier: "AddViewController") as! AddViewController
                                let newFrontViewController = UINavigationController.init(rootViewController:desController)
                                revealViewController().pushFrontViewController(newFrontViewController, animated: true)
                                return
    
                            }
                        }
                        let alertController = UIAlertController(title: "Oops!", message: "Incorrect username or password", preferredStyle: .alert)
    
                        let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                        alertController.addAction(defaultAction)
    
                        present(alertController, animated: true, completion: nil)
    
                    }
                }
            }