recently i created a post: NSData caching routine
But, now i want to be more specific in what i\'m asking.
You see, i have \"carousel\", that is actually a scrol
Got to this link: I given my answer here: Check type of class an NSData store?
Hope this helps you.
If you were to do this yourself, you could create two-tier cache system, using NSCache
and local file system. So,
At app startup, instantiate a NSCache
object.
When you need to download an image, see if image is in NSCache
.
If not, see if image is in NSCachesDirectory
folder in file system, if found here, but not in NSCache
, make sure to update NSCache
accordingly.
If found in neither NSCache
nor NSCachesDirectory
, request it asynchronously from the network (using NSURLSession
) and if you successfully found image, update both NSCache
and NSCachesDirectory
accordingly.
BTW, upon UIApplicationDidReceiveMemoryWarningNotification
, make sure to empty the NSCache
.
That might look something like:
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];
});
}
}];
}
Having said all of this, I agree with the others that it's worth trying the UIImageView
categories found in either SDWebImage and/or AFNetworking. They might do what you need, with far less work.