我目前正在从服务器下载并缓存几个不同的数据集。但是,我将所有代码从ASI交换到NSURLConneciton。我已经准备好将缓存传递给解析器委托,但是他们接受NSData类型作为参数

- (void)startTheParsingProcess:(NSData *)parserData


我的缓存类型

NSCachedURLResponse


如你所见

-(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
    if (dataSetToParse == @"a"){
        NSCachedURLResponse *aCachedResponse = cachedResponse;

        aCachedResponse = nil;
        NSDictionary *newUserInfo;
        newUserInfo = [NSDictionary dictionaryWithObject:[NSDate date] forKey:@"Cached Date"];
        aCachedResponse = [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response] data:[cachedResponse data] userInfo:newUserInfo storagePolicy:[cachedResponse storagePolicy]];
        NSLog(@"%@", aCachedResponse);
        return aCachedResponse;
    }
    if (dataSetToParse == @"b"){
        NSCachedURLResponse *bCachedResponse = cachedResponse;

        bCachedResponse = nil;
        NSDictionary *newUserInfo;
        newUserInfo = [NSDictionary dictionaryWithObject:[NSDate date] forKey:@"Cached Date"];
        bCachedResponse = [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response] data:[cachedResponse data] userInfo:newUserInfo storagePolicy:[cachedResponse storagePolicy]];
        NSLog(@"%@", bCachedResponse);
        return bCachedResponse;
    }
    return nil;

}


任何示例代码将对您有所帮助,或者只是指向正确的方向:)

我正在看苹果文档中的NSCachedURLResponse定义,它说NSCachedURLResponse具有我想要的数据,我只是不确定如何获取...与我的解析器委托一起使用。

最佳答案

你的意思是这样吗?

NSCachedURLResponse *cachedResponse = nil; // Put your code to get real response
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)[cachedResponse response];
NSData *responseData = [httpResponse data];


NSCachedURLResponse也有直接方法data,但是我无法测试它是否与上面的代码相同。

缓存建议

我看到您有自己的处理缓存的方法。如果您需要修改缓存并添加离线模式,我建议将NSURLCache子类化。如果您将其子类化并实现一些方法,例如(但不限于):

– cachedResponseForRequest:
– storeCachedResponse:forRequest:


生活对您而言可能会变得更加轻松。您只需通过[NSURLCache setSharedURLCache:[CustomURLCache new]];调用在应用程序委托中设置全局应用程序缓存。

这样,所有标准NSURL-无论什么类,其行为都将像使用系统缓存一样,并且您通常不必处理直接调用即可获取或存储缓存,系统会自动调用它们。

10-07 18:05