0

问题AFNetworking:如何知道响应是否使用缓存?AFNetworking 2.x 已很好地回答了304 或 200 。但是你如何在 3.x 中做同样的事情呢?

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

4

1 回答 1

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{}
于 2016-05-04T08:23:20.320 回答