我想在登录应用程序并收到访问令牌后对每个API调用使用访问令牌。我尝试了很多事情,但没有结果。在邮递员上进行测试时,我得到了正确的答复。我不知道我在做什么错。我正在使用AFNetworking(AFHTTPSessionManager是NetworkIntractor的基类),这是我的网络层的代码:
+(NetworkIntractor *)sharedManager{
static NetworkIntractor *manager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
config.URLCache = nil;
config.timeoutIntervalForRequest = 15.0f;
config.timeoutIntervalForResource =20.0f;
if ([USERDEFAULT boolForKey:LOGGEDIN] == YES) {
[manager.requestSerializer setValue:[[NSUserDefaults standardUserDefaults]valueForKey:AccessToken] forHTTPHeaderField:@"Authorization"];
}
manager = [[NetworkIntractor alloc]initWithBaseURL:[NSURL URLWithString:BASEURL] sessionConfiguration:config];
[manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
});
return manager;}
void call_getNetworkingAPI(NSURL *url, SuccessBlock successBlock, FailureBlock failureBlock){
NSURLSessionDataTask *task = [[NetworkIntractor sharedManager].session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error == nil) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
if (dict != nil) {
successBlock(dict,response);
}
}else
{
failureBlock(error,response);
}
}];
[task resume];
}
感谢您的帮助。
答案 0 :(得分:0)
我只是缺少标头中的缓存控制键,仅此而已。
NSDictionary *headers = @{ @"Authorization": [NSString stringWithFormat:@"Bearer %@", [[NSUserDefaults standardUserDefaults] valueForKey:AccessToken]],
@"Cache-Control": @"no-cache"
};
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", BASEURL, urlStr]]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"GET"];
[request setAllHTTPHeaderFields:headers];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
DLog(@"%@", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
DLog(@"%@", httpResponse);
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
if (dict != nil) {
successBlock(dict,httpResponse);
}
else
{
failureBlock(error,httpResponse);
}
}
}];
[dataTask resume];