我目前正在从我的服务器下载并缓存几个不同的数据集。但是我将所有代码从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;
}
任何示例代码都会有所帮助,或者只是指出我正确的方向:)
我正在查看apple docs中的NSCachedURLResponse定义,并且它说NSCachedURLResponse有我想要的数据我只是不确定如何才能得到它...与我的解析器代表一起使用。
答案 0 :(得分:1)
你的意思是什么?
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-任何类的行为就像它们使用系统缓存一样,并且您通常不必处理直接调用来获取或存储缓存,系统会自动调用它们。