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