sybohy
sybohy

Reputation: 1876

NSFileManager Not Saving

I've been trying to use NSFileManager to cache images to the Cache directory of my sandboxed app. Unfortunately, my code doesn't seem to work.

- (BOOL)saveImageToCacheFolder
{
    NSFileManager *filemgr = [NSFileManager defaultManager];
    NSString *cachePath = [[[filemgr URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject] absoluteString];
    NSString *fullpath = [cachePath stringByAppendingPathComponent:@"test.jpg"];
    NSURL *imageURL = [FlickrFetcher urlForPhoto:self.photoData format:FlickrPhotoFormatLarge];
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];

    BOOL success = false;
    if (imageData != nil) {
        success = [imageData writeToURL:[NSURL URLWithString:fullpath] atomically:true];
        if (!success) NSLog(@"Did Not Managed to save the image");
    }
    return success;
}

Here is what I am trying to do. First, get the default NSFileManager. Second, get the relative path to the cache directory of my app. Third, append the name of my file (here i just wrote test for now). Fourth, convert my image to NSData. Fourth, write the NSData object to the specified path.

edit: added if statement for checking if the imageData is nil

Upvotes: 0

Views: 871

Answers (1)

Paresh Navadiya
Paresh Navadiya

Reputation: 38249

Try this:

NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath    = [myPathList  objectAtIndex:0];
NSString *fullpath = [cachePath stringByAppendingPathComponent:@"test.jpg"];

NSURL *imageURL = [FlickrFetcher urlForPhoto:self.photoData format:FlickrPhotoFormatLarge];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];

if (imageData != nil) {
    success = [imageData writeToURL:[NSURL fileURLWithPath:fullpath] atomically:YES];
    if (!success) NSLog(@"Did Not Managed to save the image");
}

Upvotes: 3

Related Questions