create a directory in the iPhone - iphone

What's wrong with that?
#define AUDIO_NOTES_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/myApp/Pictures"]
NSFileManager *NSFm= [NSFileManager defaultManager];
BOOL isDir=YES;
if(![NSFm fileExistsAtPath:FILEPATH isDirectory:&isDir])
if(![NSFm createDirectoryAtPath:FILEPATH attributes:nil])
NSLog(#"Error: Create folder failed");

createDirectoryAtPath:attributes: is deprecated, instead you should use:
NSString *dirToCreate = [NSString stringWithFormat:#"%#/newDirectory",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
NSError *error = nil;
BOOL isDir;
if(![fm fileExistsAtPath:dirToCreate isDirectory:&isDir])
if(![fm createDirectoryAtPath:dirToCreate withIntermediateDirectories:YES attributes:nil error:&error])
NSLog(#"Error: Create folder failed");

The FILEPATH token is undefined - you #define AUDIO_NOTES_FOLDER at the beginning of your file, then use FILEPATH instead in your code.
Also note that NSHomeDirectory() isn't necessarily the recommended way of finding the Documents directory anymore - instead you probably want:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

Related

iOS : cannot delete file

I'm newbie in iOS. I have a problem.
I log the path of file and I also verify it in Finder. But fileExistsAtPath: return NO, that's why I cannot delete it.
I need help please!!
Here is the code:
+ (void)removeImage:(NSString*)imgName {
MyLog(#"%#", [Tool getFileFullPath:imgName]);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
BOOL fileExists = [fileManager fileExistsAtPath:(NSString *)[Tool getFileFullPath:imgName]];
NSLog(#"Path to file: %#", [Tool getFileFullPath:imgName]);
NSLog(#"File exists: %d", fileExists);
NSLog(#"Is deletable file at path: %d", [fileManager isDeletableFileAtPath:[Tool getFileFullPath:imgName]]);
if (fileExists)
{
BOOL success = [fileManager removeItemAtPath:[Tool getFileFullPath:imgName] error:&error];
if (!success) NSLog(#"Error: %#", [error localizedDescription]);
}
}
Path to file: /Users/vibolteav/Library/Application Support/iPhone Simulator/5.1/Applications/FD57CA70-14E4-442D-9CA5-DE7A7AD56A93/Documents/img/2053871632
File exists: 0
Is deletable file at path: 1
for remove file from document directory you use below code:
-(void)removeOneImage:(NSString*)fileName
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSLog(#"%#",fullPath);
[fileManager removeItemAtPath: fullPath error:NULL];
}
Document Path..
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentPath_ = [searchPaths objectAtIndex: 0];
Append File name...
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:fullPath])
{
NSError *error;
if (![fileManager removeItemAtPath:fullPath error:&error]) {
}
}

Create A Folder Programmatically In Xcode - Objective C

I am using the following line of code to save my file of yoyo.txt in the Documents folder ::
NSString *docDir = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSLog(#"docDir is yoyo :: %#", docDir);
NSString *FilePath = [docDir stringByAppendingPathComponent:#"yoyo.txt"];
However, I wish to save my file in a folder of yoyo i.e. inside the Documents folder i.e. I want to create another folder named as "yoyo" and then save my file of yoyo.txt into it. How can I do that ?? Thanks.
Here is a sample code (assume manager is [NSFileManager defaultManager]):
BOOL isDirectory;
NSString *yoyoDir = [docDir stringByAppendingPathComponent:#"yoyo"];
if (![manager fileExistsAtPath:yoyoDir isDirectory:&isDirectory] || !isDirectory) {
NSError *error = nil;
NSDictionary *attr = [NSDictionary dictionaryWithObject:NSFileProtectionComplete
forKey:NSFileProtectionKey];
[manager createDirectoryAtPath:yoyoDir
withIntermediateDirectories:YES
attributes:attr
error:&error];
if (error)
NSLog(#"Error creating directory path: %#", [error localizedDescription]);
}
+(void)createDirForImage :(NSString *)dirName
{
NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:dirName];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) //Does directory already exist?
{
if (![[NSFileManager defaultManager] createDirectoryAtPath:path
withIntermediateDirectories:NO
attributes:nil
error:&error])
{
NSLog(#"Create directory error: %#", error);
}
}
}
Here dataPath will be the final path for saving your file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/yoyo"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
}
dataPath = [dataPath stringByAppendingPathComponent:#"/yoyo.txt"];

copying plist to document directory

How do I copy an existing plist I have in the app build to the Document directory?
My plist is basically an array of dictionary, I have successfully copy the plist to the directory using the following:
BOOL success;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"States.plist"];
success = [fileManager fileExistsAtPath:filePath];
if (success) return;
NSString *path = [[NSBundle mainBundle] pathForResource:#"States" ofType:#"plist"];
success = [fileManager copyItemAtPath:path toPath:filePath error:&error];
if (!success) {
NSAssert1(0, #"Failed to copy Plist. Error %#", [error localizedDescription]);
}
However, when I try to access the NSDictionary it gives me:
CoreAnimation: ignoring exception: -[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object
Why is this? I have to relaunch the app again and now I can change the dictionary stored in my array
This is the way I copy the *.plist file to documents folder. Hope this helps.
+ (NSString*) getPlistPath:(NSString*) filename{
//Search for standard documents using NSSearchPathForDirectoriesInDomains
//First Param = Searching the documents directory
//Second Param = Searching the Users directory and not the System
//Expand any tildes and identify home directories.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:filename];
}
+ (void) copyPlistFileToDocument{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [Utilities getPlistPath:#"AppStatus.plist"];
if( ![fileManager fileExistsAtPath:dbPath])
{
NSString *defaultDBPath = [[NSBundle mainBundle] pathForResource:#"AppStatus" ofType:#"plist"];
BOOL copyResult = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if(!copyResult)
NSAssert1(0, #"Failed to create writable plist file with message '%#'.", [error localizedDescription]);
}
}
Just create a new pList in the documents directory, and set to the contents of the existing plist you have.

Create and save NSString data in to a file

i have 3NSString objects that i want to save to a new file when the app is running.
this will help me for remote debug!
if any one can help me creating the file and save the data to it will be very use full
thanx
You can save the files to the Documents directory, here is how to get the path to that directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
And a sample write statement:
NSError *error;
BOOL status = [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
In the NSString documentation there is method called writeToFile:atomically:encoding:error:.
NSError *error;
[#"Write me to file" writeToFile:#"<filepath>" atomically:YES encoding: NSUTF8StringEncoding error:&error];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSError *error; BOOL succeed = [myString writeToFile:[documentsDirectory stringByAppendingPathComponent:#"myfile.txt"]
atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
// Handle error here }
source.
Here is how to save NSString into Documents folder. Saving other types of data can be also realized that way.
- (void)saveString:(NSString *)stringToSave toDocumentsWithFilename:(NSString *)fileName {
NSString *documentsFolder = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *path = [documentsFolder stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] createFileAtPath:path contents:[stringToSave dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
}
Usage:
NSString *stringWeWantToSave = #"This is an elephant";
NSString *fileName = [NSString stringWithString:#"savedString.txt"];
[self saveString:stringWeWantToSave toDocumentsWithFilename:fileName];

How can I get all the file names of documents in my sandbox?

I have the following code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
However I am clueless as to how to get all the files names and assign them to an array?
Any help would be appreciated.
NSFileManager has a method called contentsOfDirectoryAtPath:error: that returns an array of all the files in that directory.
You can use it like this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if([paths count] > 0)
{
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError *error = nil;
NSArray *documentArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:&error];
if(error)
{
NSLog(#"Could not get list of documents in directory, error = %#",error);
}
}
The documentsArray object will contain a list of all the files in that directory.
Use NSFileManager's contentsOfDirectoryAtPath:error: method.
NSError *error;
NSFileManager* fileMgr = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSArray* documentsArray = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];
[documentsArray count];
Is another way of doing this for those with a different set up.