簡體   English   中英

持久登錄 iOS Objective-C

[英]Persistent login iOS Objective-C

我正在 Objective-C 中編寫一個應用程序,我有一個 API 正確地為我提供訪問令牌以保持持久登錄 state。如果用戶注銷,他們的令牌將失效並且不再存在於鑰匙串中。 但是,我在用戶打開應用程序時檢查它的最佳方式是什么?

本質上,我需要檢查用戶是否登錄? 如果是這樣,檢查並可能刷新他們的訪問令牌,並將他們帶到“X”屏幕。 如果不是,請將它們帶到登錄屏幕。

目前,我在didFinishLaunchingWithOptions function 的AppDelegate.m中有這個,如下所示:

- (void) checkLoginState {
    // Finally, is the user logged in or not?
    NSString * storyboardName = @"Main";
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
    if ([[NSUserDefaults standardUserDefaults] boolForKey:kLoggedInState]) { // if apparently logged in,
        userService = [[UserDataService alloc] init];
        [userService getUserAccountInformation:^(NSURLSessionTask * _Nonnull task, id  _Nonnull responseObject) {
            UIViewController * vc;
            if ([[NSUserDefaults standardUserDefaults] boolForKey:kCheckedInStatus]) {
                vc = [storyboard instantiateViewControllerWithIdentifier:@"TABBAR_ID"];
            } else {
                vc = [storyboard instantiateViewControllerWithIdentifier:@"VENUE_NAV_ID"];
            }
            vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            [[self window].rootViewController presentViewController:vc animated:YES completion:nil];
        } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
            // Save state  to NSUser defualts
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kLoggedInState];
            [[NSUserDefaults standardUserDefaults] synchronize];

            UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"LOGIN_ID"];
            vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            [[self window].rootViewController presentViewController:vc animated:YES completion:nil];
        }];
    } else {
        // to logout
        // Save state to NSUser defaults
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kLoggedInState];
        [[NSUserDefaults standardUserDefaults] synchronize];

        UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"LOGIN_ID"];
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        [[self window].rootViewController presentViewController:vc animated:YES completion:nil];
    }

}

這對我來說似乎很笨重,我不確定這是否是這種方法的最佳實踐。 對此有什么建議嗎? 甚至還有更簡潔的方法來編寫這段代碼嗎?

用戶信息保存在本地,可以根據用戶信息是否存在跳轉相應頁面。 對於可能出現的用戶登出事件,后端要在所有需要用戶權限的界面中添加相應的登出代碼,自己接收code代碼,並清除用戶信息並跳轉到登錄界面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM