我试图通过继承AFHTTPClient并设置基本路径来实现AFNetworking客户端
#define BaseURLString @"http://company.com/api/"
@implementation WineAPIClient
+(id)sharedInstance{
static APIClient *__sharedInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
__sharedInstance = [APIClient alloc]initWithBaseURL:[NSURL URLWithString:BaseURLString]];
});
return __sharedInstance;
}
- (id)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if(self){
[self setParameterEncoding:AFJSONParameterEncoding];
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
}
return self;
}
@end
这就是我向服务器发出请求的方式:
[[APIClient sharedInstance] getPath:@"wines"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"%@", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error fetching wines!");
NSLog(@"%@",error);
}];
现在我有了一个名为LoginViewController的类,它获取了我所携带的令牌编号。
现在我的问题是如何在我的AFHttpClinet类中将令牌设置为Authorization标头。
并使用Authorization标头进行其他请求。
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:2)
您可以使用AFNetworking
的方法
setAuthorizationHeaderWithUsername:password:
+(id)sharedInstance{
static APIClient *__sharedInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
__sharedInstance = [APIClient alloc]initWithBaseURL:[NSURL URLWithString:BaseURLString]];
[__sharedInstance setAuthorizationHeaderWithUsername:@"username" password:@"password"];
});
return __sharedInstance;
}
或强>
+(id)sharedInstance{
static APIClient *__sharedInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
__sharedInstance = [APIClient alloc]initWithBaseURL:[NSURL URLWithString:BaseURLString]];
});
return __sharedInstance;
}
- (void)updateAuthorizationHeaderUsername:(NSString *)username Password:(NSString *)password
{
[self setAuthorizationHeaderWithUsername:username password:password];
}
- (void)updateAuthorizationHeader:(NSString *)token
{
[self setDefaultHeader:@"token" value:token];
}
答案 1 :(得分:0)
尝试这样做
[[APIClient sharedInstance] getPath:@"wines"
parameters:@{@"Authorization":TOKEN}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"%@", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error fetching wines!");
NSLog(@"%@",error);
}];
TOKEN是你的标记