我在我的项目中使用基本身份验证。要获取令牌,我发送一个获取请求,获取令牌对象,将其存储为 NSUserDefault,我需要将此令牌附加到我的所有 API 调用(当然除了登录)。
在 AFNetworking/RestKit 中使用令牌进行 API 调用的正确方法是什么?
这是我的令牌对象的样子:
response.body={"Id":"84f4faf2","TokenValidity":"1.00:00:00","ValidTo":"2013-11-02T04:24:00.0817221Z","Parameters":{"AccountId":"1041"},"Token":"sF6G3czrqZmm70FtDKZxDoNC21tglUvo1+HqraqQU/Y="}
为了获得令牌,我将 AFHTTPClient 子类化并按照堆栈溢出问题Using AFNetworking and HTTP Basic Authentication中所述进行令牌调用。
目前我将响应主体存储到 id 响应对象,设置从该对象创建 NSUserDefault 并尝试调用它。
这就是我获得令牌的方式
SBAPIManager.h
#import "AFHTTPClient.h"
#import <AFNetworking/AFHTTPClient.h>
@interface SBAPIManager : AFHTTPClient
-(void)setUsername:(NSString *)username andPassword:(NSString *)password;
- (void)setAuthorizationHeaderWithToken:(NSString *)token;
+(SBAPIManager *)sharedManager;
@end
SBAPIManager.m
#import "SBAPIManager.h"
#import "AFNetworking/AFJSONRequestOperation.h"
#import "AFNetworking/AFNetworkActivityIndicatorManager.h"
@implementation SBAPIManager
#pragma mark - Methods
-(void)setUsername:(NSString *)username andPassword:(NSString *)password
{
[self clearAuthorizationHeader];
[self setAuthorizationHeaderWithUsername:username password:password];
}
-(void)setAuthorizationHeaderWithToken:(NSString *)token
{
[self setAuthorizationHeaderWithToken:token];
}
#pragma mark - initialization
-(id)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if (!self)
return nil;
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setDefaultHeader:@"Accept" value:@"application/json"];
[self setParameterEncoding:AFJSONParameterEncoding];
[[AFNetworkActivityIndicatorManager sharedManager]setEnabled:YES];
return self;
}
#pragma mark - singleton methods
+(SBAPIManager *)sharedManager
{
static dispatch_once_t pred;
static SBAPIManager *_sharedManager =nil;
dispatch_once(&pred, ^{_sharedManager =[[self alloc]initWithBaseURL:[NSURL URLWithString:@"https://qstage.azurewebsites.net"]]; });
return _sharedManager;
}
@end
视图控制器.m
[[SBAPIManager sharedManager]setUsername:_nickname andPassword:_StoreIdentifierForVendor];
[[SBAPIManager sharedManager]getPath:@"/Accounts/Token" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSUserDefaults *TokenSession = [NSUserDefaults standardUserDefaults ];
[TokenSession setObject:responseObject forKey:@"TOKEN"];
NSLog(@"JSON");
NSLog(@"token %@",[self Token]);
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
//Error stuff here
}];
} failure:nil];
}
创建 TokenSession 对象后,我对 TokenSession 进行Base64编码,并在进行 API 调用之前将其与 setAuthorizationHeaderWithToken 方法一起使用。但我得到一个[__NSCFDictionary dataUsingEncoding:]: unrecognized selector sent to instance
错误。因此,在我尝试解决此问题之前,如果有人能告诉我,我的做法是否是进行 API 调用的正确方法,我将不胜感激。