最近我创建了一个帖子:NSData缓存例程
但是,现在我想更具体地说明我的要求。
你看,我有一个"旋转木马",实际上是一个滚动视图,有7个图像。当它第一次出现时,它会从互联网上加载图像并自动滚动。
我的问题是,我不想每次滚动时都加载图像。幸运的是,有一些"缓存"机制在后台工作。所以,当它加载所有图像,然后终止应用程序,然后在没有互联网连接的情况下启动时,所有图像都已经设置好了,所以,它不知从哪里加载。
这是我使用的代码:
NSError *error;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", WEBSITE, mdl.imageSubUrl]] options:NSDataReadingUncached error:&error];;
NSLog(@"data size0? %lu", (unsigned long)data.length);
就是这样。你可能想自己尝试一下,加载一些图像,然后在飞机模式下重新启动应用程序并检查字节长度。即使在我搜索的时候,也会有数据,据说dataWithContentsOfURL
不做任何缓存。
所以,我想要的只是简单地检查,如果有数据,如果有,就不要下载
if (haveData){
self.ivPic.image = [UIImage imageWith:myData];
} else {
NSError *error;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", WEBSITE, mdl.imageSubUrl]] options:NSDataReadingUncached error:&error];;
NSLog(@"data size0? %lu", (unsigned long)data.length);
}
不幸的是,我不知道如何进行这样的测试(如果有数据的话)。其次,我不太确定如何加载存储的数据,而不是从主机启动加载的dataWithContentsOfURL。
- 首先,您应该检查类型:
-
转到这个链接:我在这里给出了答案:检查NSData存储的类类型?
希望这对你有帮助。
如果您自己做这件事,您可以使用NSCache
和本地文件系统创建两层缓存系统。所以,
-
在应用程序启动时,实例化一个
NSCache
对象。 -
当您需要下载图像时,请查看图像是否在
NSCache
中。 -
如果没有,请查看图像是否在文件系统中的
NSCachesDirectory
文件夹中,如果在此处找到,但不在NSCache
中,请确保相应地更新NSCache
。 -
如果在
NSCache
和NSCachesDirectory
中都没有找到,请从网络异步请求(使用NSURLSession
),如果成功找到映像,则相应地更新NSCache
和NSCachesDirectory
。 -
BTW,在
UIApplicationDidReceiveMemoryWarningNotification
时,确保清空NSCache
。
这可能看起来像:
NSString *filename = [webURL lastPathComponent];
NSURL *fileURL;
// look in `NSCache`
NSData *data = [self.cache objectForKey:filename];
// if not found, look in `NSCachesDirectory`
if (!data) {
NSError *error;
NSURL *cacheFileURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:false error:&error];
fileURL = [cacheFileURL URLByAppendingPathComponent:filename];
data = [NSData dataWithContentsOfURL:fileURL];
// if found, update `NSCache`
if (data) {
[self.cache setObject:data forKey:filename];
}
}
// if still not found, retrieve it from the network
if (!data) {
[[NSURLSession sharedSession] dataTaskWithURL:webURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
// handle error
return;
}
UIImage *image = [UIImage imageWithData:data];
// if image retrieved successfully, now save it
if (image) {
dispatch_async(dispatch_get_main_queue(), ^{
[self.cache setObject:data forKey:filename];
NSError *fileError;
[data writeToURL:fileURL options:NSDataWritingAtomic error:&fileError];
});
}
}];
}
说了这么多,我同意其他人的看法,即值得尝试SDWebImage和/或AFNetworking中的UIImageView
类别。他们可能会用少得多的工作来做你需要的事情。