iphone - 从 IOS 应用程序注销的完美方法是什么?

标签 iphone ios logout

下面的代码可以工作,但有一个错误。场景是,我首先登录进入应用程序系统。登录成功后,应用程序将设置 UserDefaults (UserId)。之后,我可以使用存储的 UserId 导航应用 View 。一旦我转到设置和选项卡注销,这将清除 UserId 并转到登录 View 。

BUG:当我再次登录应用程序并单击主页按钮转到 iPhone 桌面并关闭应用程序,然后返回再次打开它时,它仍然存储 UserId。因此,如果我转到设置并注销,那将清除 UserId 并且不会进入登录 View 。我不知道为什么。

代码:

- (IBAction)resetKeychain:(id)sender {

    UIActionSheet *actionSheet = [[UIActionSheet alloc] 
                 initWithTitle:@"Are you sure you want to logout?" 
                 delegate:self 
                 cancelButtonTitle:@"Cancel" 
                 destructiveButtonTitle:@"Logout"
                 otherButtonTitles:nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    [actionSheet showFromTabBar:self.tabBarController.tabBar];
    [actionSheet release];

}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex ==0) {
        //logout
        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
        //delete user ID fro user Defaults
        [defaults setObject:nil forKey:@"UserId"];
        //redirect to login view

        NewClassMoonAppDelegate * appsDelegate =[[UIApplication sharedApplication] delegate];
        [appsDelegate.window addSubview:[appsDelegate.login view]];

    }
}

最佳答案

根据我可以解释的问题,顺便说一下,这个问题需要格式化和连贯,我相信:

a) 您的 @"UserID" 值未与 NSUserDefaults 同步,因为您没有调用 -synchronize 方法。 NSUserDefaults 将更新其内存中的键值存储,但不会将其写入磁盘,这意味着它会在任意时间丢失。

b) 它不会转到 loginView 的事实可能与任何几个原因有关,很可能它已经是您的 UIWindow 的 subview 。因此,不要在应用程序委托(delegate)中重用 login 属性,而是创建 View Controller 的新实例变量,并将其设置为 rootViewController相反。

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

    if (buttonIndex == 0) {
        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:nil forKey:@"UserId"];
        [defaults synchronize];
        //redirect to login view

        NewClassMoonAppDelegate * appsDelegate =[[UIApplication sharedApplication] delegate];
        LoginViewController *login = [[LoginViewController alloc] initWithNibName...];
        [appsDelegate.window setRootViewController:nil];
        [appsDelegate.window setRootViewController:login];

    }
}

关于iphone - 从 IOS 应用程序注销的完美方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14632719/

相关文章:

iphone - UITableView 使用解析另一个页面在底部添加行

iphone - 使用导航栏在 IB 中设计 View ?

iphone - 带标签的 Xcode 链接

ios - 如何更改 UICollectionView 的选定单元格的图像?

ios - iOS 中的 Lua 和侧面加载脚本

php - facebook 从网站登录和注销?

python - Django allauth 更改密码而不注销

iphone - 私有(private) api 列表

android - 在 Windows 中获取 React Native IOS .ipa 文件

PHP:如何使用 JWT 从 API 注销