Troubling creating subdirectory of NSCachesDirectory and adding image to it - ios

EDIT: Solution at the end of the post
I'm having trouble creating a subdirectory of NSCachesDirectory and adding an NSData object to it. I've referred to multiple SO posts related to this but when I debug my code, it tells me that the NSData file in the folder doesn't exist. My code:
NSURL *photoURL = [FlickrFetcher urlForPhoto:self.singlePhotoDictionary
format:FlickrPhotoFormatLarge];
NSData *URLToData = [NSData dataWithContentsOfURL:photoURL];
NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *newDirectory = [cacheDirectory stringByAppendingPathComponent:#"Photos"];
BOOL isDir = NO;
NSError *error;
if (! [[NSFileManager defaultManager] fileExistsAtPath:newDirectory isDirectory:&isDir] && isDir == NO)
{
[[NSFileManager defaultManager]createDirectoryAtPath:newDirectory withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *filePath = [newDirectory stringByAppendingPathComponent:#"thePhotos.jpg"];
NSLog(#"%#", filePath);
//[URLToData writeToFile:filePath atomically:NO];
[[NSFileManager defaultManager] createFileAtPath:filePath contents:URLToData attributes:nil];
NSData *theData = [[NSFileManager defaultManager] contentsAtPath:filePath];
NSArray *contentsInManager = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:newDirectory error:nil];
theData and contentsInManager turn out to be:
theData NSData * 0x00000000
contentsInManager NSArray * 0x00000000
Any help here? The subdirectory exists but the file won't be created inside of it.
As a side question: When do we need to make our own instance of NSFileManager as opposed to using the defaultManager?
Thanks in advance!
SOLUTION: After trial and error, I tried deleting the subdirectory and recreating it. Once I did, the file was able to write to the subdirectory.

Related

How to copy NSData contents to temporary file?

I'm downloading what can be a large file from an S3 bucket and want to save it between view controllers to be consumed a short time later. I like the tmp directory because of less limitations on file size and there also does not seem to be a reason for me to save this in the Documents directory.
I can construct a path to tmp with:
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSURL *fileURL = [[tmpDirURL URLByAppendingPathComponent:#"image"] URLByAppendingPathExtension:#"png"];
NSLog(#"fileURL: %#", [fileURL path]);
but am unsure how to write/overwrite the downloaded NSData * to that path.
I basically just want to what I can more clearly express with the command line:
wget https://example.com/image.png
cp image.png /tmp/
Looks like the class reference may expose a method to do just this:
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/
EDIT
My solution that works. Ended up being that I needed to use writeToURL. Inspiration taken from here:
http://nshipster.com/nstemporarydirectory/
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/#//apple_ref/occ/clm/NSURL/fileURLWithPath:isDirectory:
#define S3_LATEST_IMAGE_FILEPATH #"test-image.png"
// Write the downloaded result to the filesystem
NSError *error;
NSString *fileName = [NSString stringWithFormat:#"%#_%#", [[NSProcessInfo processInfo] globallyUniqueString], S3_LATEST_IMAGE_FILEPATH];
NSURL *directoryURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]] isDirectory:YES];
[[NSFileManager defaultManager] createDirectoryAtURL:directoryURL withIntermediateDirectories:YES attributes:nil error:&error];
if (error) {
NSLog(#"Error1: %#", error);
return;
}
NSURL *fileURL = [directoryURL URLByAppendingPathComponent:fileName];
NSString *path = fileURL.absoluteString;
NSLog(#"fileURL.absoluteString: %#", path);
[data writeToURL:fileURL options:NSDataWritingAtomic error:&error];
if (error) {
NSLog(#"Error: %#", error);
}
You can directly write the NSData into the path by
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSURL *fileURL = [[tmpDirURL URLByAppendingPathComponent:#"newest-fw"] URLByAppendingPathExtension:#"zip"];
NSString *path= fileURL.absoluteString;
//data would be the NSData that you get from the S3 bucket
NSError *error;
[[NSFileManager defaultManager] createDirectoryAtURL: fileURL withIntermediateDirectories:NO attributes:nil error:&error];
[data writeToFile:path options:NSDataWritingAtomic error:&error];
NSData's writeToFile method will automatically overwrite the file if it is previously present.

iCloud data uploading is not working when .sqlite file is uploaded in ios

I am trying to upload sqlite file on iCloud. I am using NSFileCoortinator for coping the file from one file to another file but schema of sqlite file is only get copied, I am not getting data in sqlite file….Also sometimes the data is appearing in the sqlite file on iCloud. I don’t understand why this is happening. Is this sqlite file issue or I did wrong in code. If anyone has solution please help me out.
-(void)uploadFile
{
//-------code for uploading data to icloud
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,
NSUserDomainMask, YES);
NSString *applicationSupportDirectory = [paths firstObject]
NSString *str=[NSString stringWithFormat:#"%#/XMPPMessageArchiving.sqlite",applicationSupportDirectory]; //copy this file
NSString *fileName = [NSString stringWithFormat:#"XMPPMessageArchiving.sqlite"];
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
NSURL *fromURL = [NSURL fileURLWithPath:str];
NSURL *toURL = [[ubiq URLByAppendingPathComponent:#"Documents"]
URLByAppendingPathComponent:fileName];;
[coordinator coordinateReadingItemAtURL:fromURL options:0 writingItemAtURL:toURL options:NSFileCoordinatorWritingForReplacing error:nil byAccessor:^(NSURL *newReadingURL, NSURL *newWritingURL)
{
NSError *error=nil;
NSData *data = [[NSFileManager defaultManager] contentsAtPath:fromURL.path];
//if file is already present on icloud replace that file with new file
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:newWritingURL.path];
if (fileExists)
{
[[NSFileManager defaultManager] removeItemAtPath:toURL.path error:NULL];
}
BOOL isCopied= [[NSFileManager defaultManager] copyItemAtPath:newReadingURL.path toPath:newWritingURL.path error:nil];
NSLog(#"file copied= %d",isCopied);
}];
}
The value for file copied is always 1 but still data is not available.

iOS - Saved file missing

I tried saving a file into NSLibraryDirectory with the below code:
if (!userDir) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
documentsDirectory = [[[documentsDirectory stringByAppendingPathComponent:#"Caches"] stringByAppendingPathComponent:#"account"] stringByAppendingPathComponent:#"test"];
NSString *imageDir = [[documentsDirectory stringByAppendingPathComponent:#"Root"] stringByAppendingPathComponent:#"imageType"];
NSError *error = nil;
BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:imageDir withIntermediateDirectories:YES attributes:nil error:&error];
NSString *fileName = #"avatar"
NSString filePath = [imageDir stringByAppendingPathComponent:fileName];
}
NSData *imagedata = **imagedata**
NSError *saveError = nil;
[imageData writeToFile:filePath options:NSDataWritingWithoutOverwriting error:&saveError];
Image is saved and I can load it using the following method:
NSError *error = nil;
NSData *imageData = [[NSData alloc] initWithContentsOfFile:filePath options:NSDataReadingUncached error:&error];
When I kill the app and launch it again, the file is missing. Am I doing anything wrong here?
You're saving it in the Caches directory, which the system may clear whenever your app is not running. If you want the file to stick around more permanently you should store it somewhere else, like the Documents directory.

save picture in folder which is located in document direcotory in iphone

i want to create folder in document directory and want to save images in that folder. i have tried but the folder and the images are storing in document directory..But i want to store the images inside the folder.my code is working fine but the images are not saving inside Folder..
NSError *error;
NSString *aDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *dataPath = [aDocumentsDirectory stringByAppendingPathComponent:#"Folder"];
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
NSInteger anIndex = 0;
for (UIImage *anImage in _chosenImages)
{
NSString *anImageName = [NSString stringWithFormat:#"%d.png", anIndex++];
NSString *anImagePath = [NSString stringWithFormat:#"%#/%#", aDocumentsDirectory, anImageName];
NSLog(#"the path is=%#",anImagePath);
NSData *anImageData = UIImagePNGRepresentation(anImage);
[anImageData writeToFile:anImagePath atomically:YES];
}
I guess your "anImagePath" is still pointing to documents directory.
edit it as "dataPath" as the argument as below
NSString *anImagePath = [NSString stringWithFormat:#"%#/%#", dataPath, anImageName];
try this..
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&error];
actually you arr passing NO in "withIntermediateDirectories" parameter, and if you pass NO to this than if any of the intermediate parent directories does not exist. This method also fails if any of the intermediate path elements corresponds to a file and not a directory.

Remove all files from memory using NSFileManager

How can you remove all the files that are saved using the NSFileManager ? I found something like the code below, but you need to give the filePath and since I need to delete all the images that I've saved, I don't know all the image paths/names?
[[NSFileManager defaultManager] removeItemAtPath:filePath error:NULL];
First get all the item from that particular folder :
NSString *filePath = [NSString stringWithFormat:#"your folder path where you have saved those images"];
NSArray *files = [fileManager contentsOfDirectoryAtPath:filePath
error:nil];
this will be the array of the files just loop through the array .and use:
for(NSString *filename in files)
{
NSString *filePath = [NSString stringWithFormat:#"filepath/%#",filename];
[[NSFileManager defaultManager] removeItemAtPath:filePath error:NULL];
}
This should do the trick.
You must be saving your images to any of the folders like, Documents Directory, Library, Caches, or Temp folders. You need to fetch all the images inside any of your directory where you have saved your images using following code..
-(NSArray*)getImagesFromDirectory:(NSString*)imageDirectoryPath{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *files = [fileManager contentsOfDirectoryAtPath:imageDirectoryPath
error:nil];
return files;
}
Then loop to remove images at path
NSArray *images=[self getImagesFromDirectory:#"DIRECTORYPATH"];
NSFileManager * fileManager = [[NSFileManager alloc] init];
for(NSString *imagePath in images){
[fileManager removeItemAtPath:imagePath];
}

Resources