我是iOS用户并使用基本应用程序时,它目前正与SSKeychain
和AFNetworking
合作,以便与API进行交互。当您使用我检索的应用程序登录并在我的CredentialStore类中设置auth_token时,我需要将身份验证令牌作为http标头发送到API以获取访问权限。如何检索我在HomeViewController中的CredentialStore类中存储的令牌。
这是我的CredentialStore:
#import "GFCredentialStore.h"
#import "SSKeychain.h"
#define SERVICE_NAME @"Groupify"
#define AUTH_TOKEN_KEY @"auth_token"
@implementation GFCredentialStore : NSObject
- (BOOL)isLoggedIn {
return [self authToken] != nil;
}
- (void)clearSavedCredentials {
[self setAuthToken:nil];
}
- (NSString *)authToken {
return [self secureValueForKey:AUTH_TOKEN_KEY];
}
- (void)setAuthToken:(NSString *)authToken {
[self setSecureValue:authToken forKey:AUTH_TOKEN_KEY];
[[NSNotificationCenter defaultCenter] postNotificationName:@"token-changed" object:self];
}
- (void)setSecureValue:(NSString *)value forKey:(NSString *)key {
if (value) {
[SSKeychain setPassword:value
forService:SERVICE_NAME
account:key];
} else {
[SSKeychain deletePasswordForService:SERVICE_NAME account:key];
}
}
- (NSString *)secureValueForKey:(NSString *)key {
return [SSKeychain passwordForService:SERVICE_NAME account:key];
}
@end
这里我试图检索authToken值并将其设置为字符串,以便我可以将其作为http标头发送:
#import "GFHomeViewController.h"
#import <AFNetworking.h>
#import "GFCredentialStore.h"
#define kBaseURL "http://localhost:3000/"
#define kHomeURL "newsfeed.json"
@interface GFHomeViewController ()
@end
@implementation GFHomeViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
__weak typeof(self)weakSelf = self;
NSString *urlString = [NSString stringWithFormat:@"%s%s", kBaseURL, kHomeURL];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue: forHTTPHeaderField:@"auth_token"];
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}
答案 0 :(得分:1)
假设SSKeychain
正在保存并从钥匙串返回值,我认为你只能做这样的事情
GFCredentialStore *credentialStore = [[CGCredentialStore alloc] init];
if ([credentialStore isLoggedIn]) {
NSString *authToken = [credentialStore authToken];
[manager.requestSerializer setValue:authToken forHTTPHeaderField:@"auth_token"];
} else {
// prompt/display controller for login
}
如果我在您遇到的问题/问题中遗漏了某些内容,请澄清您的问题,我还会再次提出问题。