【发布时间】:2015-05-01 17:07:49
【问题描述】:
我将我的应用程序连接到一个 REST API 以登录用户。登录过程完成后,我使用 NSNotificationCenter 通知控制器登录成功,并让应用程序执行 segue 以将用户带到主菜单。这是我的代码:
//perform log in, or show error message
-(void)logInAttemptComplete:(NSNotification *)notification
{
Boolean loginSuccessful = (Boolean)[[notification userInfo] objectForKey:@"loginSuccessful"];
[SVProgressHUD dismiss];
//if the suer was successfully logged in, take him to the main menu
if(loginSuccessful)
{
//go to the main menu
[self performSegueWithIdentifier:@"logInSuccessfulSegue" sender:self];
}
else
{
//copy error code and display appropriate error
int errorCode = [[[notification userInfo] objectForKey:@"HTTP Message"] intValue];
//404 no server, 401 wrong password/no user
if(errorCode==401)
{
//create and show error alert view
UIAlertView *loginErrorAlertView = [[UIAlertView alloc] initWithTitle:@"Log In Failure" message:@"Wrong credentials. Check your Username and/or Password." delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[loginErrorAlertView show];
}
else
{
//create and show error alert view
UIAlertView *loginErrorAlertView = [[UIAlertView alloc] initWithTitle:@"Log In Failure" message:@"Failed to contact server, please try again later." delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[loginErrorAlertView show];
}
}
}
问题是,如果第一次尝试登录不成功,假设需要 X 次尝试才能成功登录,那么 segue 会执行 X 次。当然,它确实出现在主菜单上,但最终结果很丑陋。任何想法如何解决这一问题?也许我应该避免使用 segue 并以编程方式将 hte 用户直接带到另一个控制器?
编辑回答
所以我通过添加行出错了
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logInAttemptComplete:) name:@"logInNotification" object:nil];
在按下登录按钮的功能内。
我通过在登录尝试失败后删除观察者来修复它
if(loginSuccessful)
{
//go to the main menu
[self performSegueWithIdentifier:@"logInSuccessfulSegue" sender:self];
}
else
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"logInNotification" object:nil];
【问题讨论】:
标签: ios objective-c iphone segue nsnotificationcenter