I am trying to use NSFileManager to move a file from the Documents/Inbox folder to the Documents folder. I used breakpoints to figure out where my code wasn't working, and everything seemed to be running fine until it hit the part where it actually moves the files. The directories are found and the files are noted in the debugger, but it just won't move. Here is my entire viewDidLoad method (there's nothing in [super viewDidLoad];):
//Turn every file inside the directory into an array
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *appFolderPath = [path objectAtIndex:0];
NSString *inboxAppFolderPath = [appFolderPath stringByAppendingString:#"/Inbox"]; //changes the directory address to make it for the inbox
//NSPredicates to filter out files I don't want in my NSArray
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"not SELF beginswith[c] '.DS_Store'"];
NSPredicate *inboxPredicate = [NSPredicate predicateWithFormat:#"not SELF beginswith[c] 'Inbox'"];
recipes = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:appFolderPath error:nil];
recipes = [recipes filteredArrayUsingPredicate:predicate];
recipes = [recipes filteredArrayUsingPredicate:inboxPredicate];
//get to inbox directory
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *inboxContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSString stringWithFormat:inboxAppFolderPath,documentsDirectory] error:nil];
//move all the files over
for (int i = 0; i != [inboxContents count]; i++)
{
NSString *oldPath = [NSString stringWithFormat:inboxAppFolderPath, documentsDirectory, [inboxContents objectAtIndex:i]];
NSString *newPath = [NSString stringWithFormat:appFolderPath, documentsDirectory, [inboxContents objectAtIndex:i]];
[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:nil];
}
There may be issue for creating sub folder inside Documents.
Try to create inboxAppFolder in this manner.
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *inboxAppFolderPath = [path stringByAppendingPathComponent:#"Inbox"]; // subDirectory
if (![[NSFileManager defaultManager] fileExistsAtPath: inboxAppFolderPath])
[[NSFileManager defaultManager] createDirectoryAtPath: inboxAppFolderPath withIntermediateDirectories:NO attributes:nil error:nil];
//Rest of your code
Hope, it'll help you.
Thanks.
Related
This question already has an answer here:
Delete a file from the partial string xcode
(1 answer)
Closed 7 years ago.
I have files such as:
RN150622103444544_pr.pdf
RN150622103444544_ID_GD.pdf
RN150622103444544_CA.xml
My question is how can I delete all the files only by referring the RN150622103444544 part of their name by using NSPredicate.
Currently my code is deleting one by one:
-(void)deleteOldPdfs:(NSString *)proposal
{
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if([fm fileExistsAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_pr_1.pdf",proposal]]])
[fm removeItemAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_pr_1.pdf",proposal]] error:&error];
if([fm fileExistsAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_id_GD.pdf", proposal]]])
[fm removeItemAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_id_GD.pdf", proposal]] error:&error];
if([fm fileExistsAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_CA.xml", proposal]]])
[fm removeItemAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_CA.xml",proposal]] error:&error];
}
You could use something like the following which lists the contents of the directory and then filters those contents using a NSPredicate to only the paths containing your label.
- (void) deleteFilesContainingLabel:(NSString *)label{
NSFileManager *fm = [NSFileManager defaultManager];
// Get the root directory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// Create a predicate to filter out file paths containing the required
// label.
NSPredicate *filter = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"self CONTAINS '%#'",label]];
// List the directory
NSArray *dirContents = [fm contentsOfDirectoryAtPath:documentsDirectory error:nil];
// Filter the list using our predicate
NSArray *filteredFiles = [dirContents filteredArrayUsingPredicate:filter];
// Delete the files which pass the predicate filter.
NSError *error;
for (NSString *path in filteredFiles){
[fm removeItemAtPath:path error:&error];
}
}
I want to add a list of Files in Document Directory to an Array of Strings. Not sure exactly how to do this, this is what I have so far. I want to load/store only the files that contain the word 'bottom' in the filename in the array. How do i do this exactly?
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fileMan = [[NSFileManager alloc]init];
NSArray *files = [fileMan contentsOfDirectoryAtPath:documentsDirectory error:nil];
for(int i =0; i<files.count; i++){
}
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString rangeOfString:#"bottom"]];
//THIS IS HARDCODED ARRAY OF FILE-STRING NAMES
NSArray *bottomArray =[NSArray arrayWithObjects: #"bottom6D08B918-326D-41E1-8A47-B92F80EF07E5-1240-000005EB14009605.png", #"bottom837C95CF-85B2-456D-8197-326A637F3A5B-6021-0000340042C31C23.png", nil];
You need to check each file in the files array:
NSFileManager *fileMan = [NSFileManager defaultFileManager];
NSArray *files = [fileMan contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSMutableArray *bottomArray = [NSMutableArray array];
for (NSString *file in files) {
if ([file rangeOfString:#"bottom"].location != NSNotFound) {
[bottomArray addObject:file];
}
}
In addition to #rmaddy's approach, another option is to use an instance of NSPredicate to filter the array of file names:
NSArray *filenames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"self contains 'bottom'"];
NSArray *matchedNames = [filenames filteredArrayUsingPredicate:predicate];
I am creating a directory inside my application.Is there a code to view the contents of the directory in xcode. For example in android you can create a custom directory and view its contents using a file manager application. Can the similar procedure be done in apple?
Here is the code which i use to create a directory?
bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
fileManager = [NSFileManager defaultManager];
myImageDirectory = [fileManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask];
if ([myImageDirectory count] == 1){
NSLog(#"myImageDirectoryIs already present directory is already present");
}else{
directoryPath = [[myImageDirectory objectAtIndex:0] URLByAppendingPathComponent:bundleIdentifier];
NSLog(#"myImageDirectory directory name = %#",[directoryPath absoluteString]);
NSError *theError = nil;
if (![fileManager createDirectoryAtURL:directoryPath withIntermediateDirectories:NO attributes:nil error:&theError]){
NSLog(#"didnt write image data");
}else{
imagePath = [[directoryPath absoluteString] stringByAppendingPathComponent:[NSString stringWithFormat:#"/%#_%#_%#_image.jpg",dIdNo,iIdNo,[self currentDateandTime]]];
[imageData writeToFile:imagePath atomically:YES];
}
}
If your app is running in the simulator you'll need to use Finder. Go to the following directory:
/Users/<username>/Library/Application Support/iPhone Simulator/<iOS version>/Applications/<uuid>/Library/Application Support
If your app is running on the device you can use Xcode:
Connect the device
Choose menu option Window -> Organizer
Go to the Devices Tab
Click Applications under the device menu on the left
Pick your Application
The directory contents will be listed and you can optionally download everything.
try this...
to create a directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
to retrieve contents from directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *customDirectory = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
NSError * error;
NSArray *directoryContents = [[NSFileManager defaultManager]
contentsOfDirectoryAtPath:customDirectory error:&error];
for(NSString *strFile in directoryContents)
{
NSString *strVideoPath = [NSString stringWithFormat:#"%#/%#",customDirectory,strFile];
if([[strVideoPath pathExtension] isEqualToString:#"mp4"] || [[strVideoPath pathExtension] isEqualToString:#"mov"])
{
[urlArray addObject:strVideoPath];
}
}
you can get the contents of the directory(MYNewFolder) from below code:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"MYNewFolder"];
NSArray *filePathsArray = [[NSFileManager defaultManager]
subpathsOfDirectoryAtPath:stringPath
error:nil];
for ( NSString *apath in filePathsArray )
{
NSLog(#"inside the file path array=%d",apath);
}
Method
-(NSArray *) getObjectsInDirectory:(NSString *)directory {
NSFileManager * fm = [NSFileManager defaultManager];
NSError * error = nil;
NSArray * result = [fm contentsOfDirectoryAtPath:directory error:&error];
return result;
}
How-To
NSString * documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray * files = [self getobjectsInDirectory:documentsPath];
This code is used to get an array of the files within the documents directory.
Viewing the Files
NSLog(#"%#", files);
Check this class out, it allows you to simplify so many things in iOS: Atomic Class
I am saving an image however it is just duplicating itself since I only set only one name however I want it to count up so that it wont replace itself. Is there any way to do this?
NSArray *directoryNames = [NSArray arrayWithObjects:#"hats",#"bottoms",#"right",#"left",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
for (int i = 0; i < [directoryNames count] ; i++) {
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[directoryNames objectAtIndex:i]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; //Create folder
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:#"hats"]; // "right" is at index 2, per comments & code
NSString *filePath = [folderPath stringByAppendingPathComponent:#"hats.PNG"]; // you maybe want to incorporate a timestamp into the name to avoid duplicates
NSData *imageData = UIImagePNGRepresentation(captureImage.image);
[imageData writeToFile:filePath atomically:YES];
}
Use timestamp value as filename to avoid duplicates
I've spent the past few hours trying to figure this out, but I've ran out of ideas.
All I'm trying to do is archive an object, but the method archiveRootObject keeps on returning NO
Here's my code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [paths objectAtIndex:0];
cacheDirectory = [cacheDirectory stringByAppendingPathComponent:#"MyAppCache"];
NSString *fullPath = [cacheDirectory stringByAppendingPathComponent:#"archive.data"];
if(![[NSFileManager defaultManager] fileExistsAtPath:fullPath]){
[[NSFileManager defaultManager] createDirectoryAtPath:fullPath withIntermediateDirectories:YES attributes:nil error:nil];
}
NSArray *array = [NSArray arrayWithObjects:#"hello", #"world", nil];
NSLog(#"Full Path: %#", fullPath);
BOOL res = [NSKeyedArchiver archiveRootObject:array toFile:fullPath];
if(res){
NSLog(#"YES");
}else{
NSLog(#"NO");
}
Every time time I run this, it prints NO.
Any help would be appreciated!
You create a directory with the path fullPath and then you try to write the file at the same path. Overwriting a directory with a file like this is not possible. Use your cacheDirectory string to create your directory.
NSString *cacheDirectory is not a mutable string and after you init it, you attempt to modify it so you are writing to the top-level directory.
For a quick fix, try:
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentPath = ([documentPaths count] > 0) ? [documentPaths objectAtIndex:0] : nil;
NSString *documentsResourcesPath = [documentPath stringByAppendingPathComponent:#"MyAppCache"];
NSString *fullPath = [documentsResourcesPath stringByAppendingPathComponent:#"archive.data"];