gpt4 book ai didi

iOS 检索 valueForKey?

转载 作者:行者123 更新时间:2023-11-29 03:06:24 28 4
gpt4 key购买 nike

我是 iOS 的新手,正在开发一个基本的应用程序,它目前正在使用 SSKeychainAFNetworking 与 API 进行交互。当您使用我检索的应用程序登录并在我的 CredentialStore 类中设置 auth_token 时,我需要将 auth token 作为 http header 发送到 API 以获得访问权限。如何检索存储在 HomeViewController 的 CredentialStore 类中的 token 。

这是我的 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 header 发送:

#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);
}];

}

最佳答案

假设 SSKeychain 正在保存钥匙串(keychain)并向/从钥匙串(keychain)返回值,我认为您可以简单地执行类似的操作

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
}

如果我遗漏了您遇到的问题/问题中的某些内容,请澄清您的问题,我会再次尝试解决。

关于iOS 检索 valueForKey?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22724954/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com