我遇到了登录 API 的问题。第一次调用工作正常,但后续调用被缓存。这导致了一个问题,因为登录/注销功能基本上被破坏了。
我尝试了很多方法,并且正在实现 AFNetworking 库。
在AppDelegate.m
:
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0
diskCapacity:0
diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
在我的网络课上:
(AFHTTPRequestOperation *)createRequestOperationWithMethod:(NSString *) method andPath: (NSString *)path andParams:(NSDictionary *)params
{
GRAPIClient *httpClient = [GRAPIClient sharedClient];
[httpClient setParameterEncoding:AFFormURLParameterEncoding];
NSMutableURLRequest *request = [httpClient requestWithMethod:method
path:path
parameters:params];
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData]
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
return operation;
}
我什至试图覆盖在 AFHTTPClient 中生成的请求
在 AFHTTPClient.m 中:
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[request setTimeoutInterval:2.0];
我的 GRAPIClient 实现:
@interface GRAPIClient : AFHTTPClient
+ (GRAPIClient *)sharedClient;
+ (BOOL) isInternetReachable;
@end
@implementation GRAPIClient
+ (BOOL) isInternetReachable
{
return reachable;
}
+ (GRAPIClient *)sharedClient {
static GRAPIClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[GRAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kAFAppDotNetAPIBaseURLString]];
});
[_sharedClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
if (status == AFNetworkReachabilityStatusReachableViaWWAN ||
status == AFNetworkReachabilityStatusReachableViaWiFi ) {
NSLog(@"Reachable on!");
reachable = YES;
}
else
{
NSLog(@"Reachable off!");
reachable = NO;
}
}];
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
// Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:@"Accept" value:@"application/json"];
return self;
}
@end
我已经调试了来自服务器的响应,并通过同时将两个 NSURLRequest 硬编码到服务器进行了测试。一个用于用户 A,一个用于用户 B,然后打印两个用户的响应数据。
首次登录时,用户 A 登录返回用户 A 凭据。用户 B 返回了用户 B 凭据。在第二次登录时,用户 A 返回用户 A 凭据,用户 B 返回用户 A 凭据。我不知道如何完全禁用缓存。