【问题标题】:cachedResponseForRequest method not being accessedcachedResponseForRequest 方法未被访问
【发布时间】:2025-11-27 08:15:02
【问题描述】:

我正在尝试设置缓存,但是线程没有访问我正在使用的“如下”方法。

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

我正在像这样初始化连接,并且访问了 connectionDidFinishLoading,所以我不确定我缺少什么。

- (IBAction)searchRequest:(NSData *)postBodyData
{
    //Set database address
    NSMutableString *databaseURL = [[NSMutableString alloc] initWithString:@"https://127.0.0.1:88"]; 

    NSURL *url = [NSURL URLWithString:databaseURL];

    NSString *postLength = [NSString stringWithFormat:@"%d", [postBodyData length]];

    //SynchronousRequest to grab the data, also setting up the cachePolicy
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0]; //if request dose not finish happen within 60 second timeout.

//    NSInputStream *fileStream = [NSInputStream inputStreamWithData:postBodyData];


    [request setHTTPMethod: @"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/octet-stream" forHTTPHeaderField:@"content-type"];
    [request setHTTPBody:postBodyData];

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (theConnection) {
        // Create the NSMutableData to hold the received data.
        // receivedData is an instance variable declared elsewhere.
        receivedData = [NSMutableData data];
    } else {
        // Inform the user that the connection failed from the connection:didFailWithError method
    }
}

任何帮助将不胜感激。

【问题讨论】:

    标签: iphone ios nsurlconnection nsurlcache


    【解决方案1】:

    connection:willCacheResponse: 仅在响应将被缓存时调用。在大多数情况下,POST 请求是不可缓存的。 (更多详情:Is it possible to cache POST methods in HTTP?

    您可能应该查看MKNetworkKit 之类的东西,它处理大量此类缓存,尤其是对于 REST 协议。

    您也可以查看Drop-in offline caching for UIWebView。您必须对其进行重大修改,但NSURLProtocol 可用于解决此类问题。 AFCache 目前正在努力整合这种方法,并且是另一个需要考虑的工具包。 (通读博文中的 cmets 以了解有关这些问题的更多背景信息。)

    【讨论】:

    • 哦,伙计,那真是个混蛋……我以为我快疯了,因为我以前用过这种方法……只是没有使用 POST 请求……感谢您的回复。最后一个问题,关于这些 3rd 方解决方案,我是否需要担心将来对它的支持,就像 ASIHTTPRequest 以及开发人员如何放弃该项目一样......
    • 你总是不得不担心任何事情。您还必须担心 Apple 会弃用您正在使用的东西。如果这与开源项目有关,您应该查看代码并决定是否愿意自己修复错误。如果是这样,那么风险很小。
    • 老师,你能看看URLresponse is not retrieved after storing in cache using storeCachedResponse吗?这已经困扰了我整整一周。