3

我正在开发一个涉及从网络服务器下载数据的 iPhone 应用程序。connection:willCacheResponse:除了永远不会调用该方法之外,所有事情都运行良好。但其他人喜欢connection:didReceiveResponse:, connection:didReceiveData:, connection:didFailWithError:,connectionDidFinishLoading:都工作正常。我进行了如下连接:

- (void)makeConnection
{
    NSURL *url = [NSURL URLWithString:@"http://www.abc.com"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
    [request setHTTPMethod:@"POST"];
    NSString *postString = [NSString stringWithFormat:@"%@", string];
    [request setValue:[NSString stringWithFormat:@"%d", [postString length]] forHTTPHeaderField:@"Content-length"];
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
    NSCachedURLResponse *newCachedResponse = cachedResponse;
    NSDictionary *newCachedResponseUserInfo = [NSDictionary dictionaryWithObject:[NSDate date] forKey:@"Cached Date"];
    newCachedResponse = [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response] data:[cachedResponse data] userInfo:newCachedResponseUserInfo storagePolicy:[cachedResponse storagePolicy]];

    return newCachedResponse;
}

我也尝试将策略更改为NSURLRequestUseProtocolCachePolicy,但没有任何帮助。还试图在

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse

但什么也没发生。我错过了什么吗?先感谢您。

4

1 回答 1

6

根据Apple 的文档,connection:willCacheResponse: 仅在响应包含 Cache-Control 标头时才调用:

委托仅接收支持缓存的协议的 connection:willCacheResponse: 消息。

于 2012-08-16T05:34:55.163 回答