Первым контроллером представления для моего приложения является HomeView, который отображает важную для пользователя информацию. Если пользователь не вошел в систему, пользовательский интерфейс представит контроллер вида просмотра LoginView, предлагающий пользователю войти в систему.Экран входа в систему отключен и снова появляется при неудачном входе в систему
Проблема заключается в том, что пользователь вводит неверные учетные данные для входа в систему, попадает в систему входа, приложение представляет ошибку. Как только ошибка будет удалена, приложение отклонит LoginView и снова представит LoginView. Поведение должно быть просто предупреждением, а затем оставить LoginView вверх.
1) Из HomeView (первоначальное представление контроллера)
override func viewWillAppear(animated: Bool) {
if (PFUser.currentUser()?.username == nil) {
dispatch_async(dispatch_get_main_queue(), {() -> Void in
let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("LoginView")
//self.showViewController(viewController, sender: self)
self.presentViewController(viewController, animated: true, completion: nil)
})
}
}
2) От LoginView проверки учетных данных пользователя, а затем войти в попытку с синтаксического анализа.
@IBAction func loginButton(sender: AnyObject) {
let username = usernameField.text?.lowercaseString
let password = passwordField.text
if username == "" || password == "" {
displayAlert("Error in form", message: "Please enter a username and password")
} else if username?.characters.count < 5 {
self.displayAlert("Failed Signup", message: "Username must be greater than 5 characters")
} else if password?.characters.count < 8 {
self.displayAlert("Failed Signup", message: "Password must be greater than 8 characters")
} else {
activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
PFUser.logInWithUsernameInBackground(username!, password: password!, block: { (user, error) -> Void in
//Kill spinner
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if ((user) != nil) {
dispatch_async(dispatch_get_main_queue(), {() -> Void in
let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("HomeView")
self.presentViewController(viewController, animated: true, completion: nil)
})
} else {
self.displayAlert("Failed Signup", message: "\(error)")
}
})
}
}
EDIT:
3) displayAlert Функция
func displayAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction((UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
})))
self.presentViewController(alert, animated: true, completion: nil)
}
Я должен отметить, что мой дом вид контроллера является частью SWRevealViewController с меню на боковой панели. Контроллер навигации для SWRevealViewController в качестве контроллера начального вида
Можете ли вы разместить функцию 'displayAlert'? – pbush25
@ pbush25 Отредактирован вопрос, чтобы добавить функцию displayAlert – Manstof