Search code examples
objective-cxcodensurlnsfilemanagerdirectory

How to write items to a directory and call them, Objective c


Hi I have a bunch of photos that I download from the web and I want to store them in a directory so I dont have to reload photos already downloaded, I am having trouble understanding how exactly to do this and store the photos and reload them from the directory and such. This is what I have so far. Could someone please explain the steps involved and how to do it? Thanks

-(void) savePhotoInCache: (NSData*) photoToSave{
   //I dont know if u need bundle ID?
   // NSString * bundleID = [[NSBundle mainBundle] bundleIdentifier];
NSFileManager *fm = [[NSFileManager alloc] init];
NSArray * directoryPaths = [fm URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
NSLog(@"%@", directoryPaths);
NSURL* dirPath = nil;    
 //Does this create a file in my cache Directory to store my photos?
dirPath = [[directoryPaths objectAtIndex:0] URLByAppendingPathComponent:[NSString stringWithFormat:@"photos.jpg"]];
NSError* theError = nil;
[fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES attributes:nil error:&theError];
// Saves the photo to the file?
[photoToSave writeToURL: dirPath atomically:NO];

NSLog(@"%@", dirPath);
//I get a deprecated warning, new version needs encoding, but I did not specify encoding in writeToURL so what do I use?
NSString * contents = [NSString stringWithContentsOfURL:dirPath ];

//After this how to I access my files and check what the contents of the file are? also, how do I limit the amount of information it stores? thanks

}

Solution

  • check this to how to get saved contents like this:

    NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dirPath error:nil];
    

    Now filter contains like this:

    NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.jpg'"];
    NSPredicate *fltr1 = [NSPredicate predicateWithFormat:@"self ENDSWITH '.png'"];
    NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:fltr];
    NSArray *onlyPNGs = [dirContents filteredArrayUsingPredicate:fltr1];
    

    To get all image content

    for(NSString *fileName in dirContents)
    {
        NSString *imgPath = [dirPath stringByAppendingFormat:fileName];
        UIImage *img = [UIImage imageWithContentsOfFile:imgPath];
        //You have image use it where u want
    }
    

    If u have many images then use lazy loading of images