AFNetworking 3.x:如何知道响应是否来自缓存?

时间:2016-02-10 13:34:37

标签: afnetworking afnetworking-3

问题AFNetworking : How to know if response is using cache or not ? 304 or 200已经为AFNetworking 2.x得到了很好的回答。但是你如何在3.x中做同样的事情?

了解在调试时是从缓存还是从网络返回资源非常有用。

1 个答案:

答案 0 :(得分:1)

您可以使用AFNetworking3.0采用相同的方法。

 BOOL __block responseFromCache = YES; // yes by default
 [self setDataTaskWillCacheResponseBlock:^NSCachedURLResponse * _Nonnull(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSCachedURLResponse * _Nonnull proposedResponse) {
    responseFromCache = NO;
    NSLog(@"Sending back to cache response");
    NSCachedURLResponse * responseCached;
    NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *)      [proposedResponse response];

    if (dataTask.originalRequest.cachePolicy == NSURLRequestUseProtocolCachePolicy) {
        NSDictionary *headers = httpResponse.allHeaderFields;
        NSString * cacheControl = [headers valueForKey:@"Cache-Control"];
        NSString * expires = [headers valueForKey:@"Expires"];
        if (cacheControl == nil && expires == nil) {
            NSLog(@"Server does not provide info for cache policy");
            responseCached = [[NSCachedURLResponse alloc] initWithResponse:dataTask.response
                                                                      data:proposedResponse.data
                                                                  userInfo:@{ @"response" : dataTask.response, @"proposed" : proposedResponse.data }
                                                             storagePolicy:NSURLCacheStorageAllowed];
        }
    }
    return responseCached;
}];

[self wb_GET:url parameters:nil headerFields:additionalHeadersDict success:^(NSURLSessionDataTask *task, id responseObject) {

        if (responseFromCache) {
            // response was returned from cache
            NSLog(@"RESPONSE FROM CACHE: %@", responseObject);
        }

    handler(responseObject, nil);

} failure:^(NSURLSessionDataTask *task, NSError *error) {
    handler(nil, error);
}];

除此之外,您还可以在AFHTTPSessionManager子类中实现以下委托方法。

  - (void)baseSuccessWithResponseObject:(id)responseObject sessionTask: (NSURLSessionDataTask *) task validationHandler:(void(^)(id responseObject, NSError *error))handler{}