iOS : cannot delete file - iphone

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]) {
}
}

Related

Append binary data to file

in my iPhone application I need to append binary data to file:
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSData* data = [NSData dataWithBytes:buffer length:readBytes_];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"myFile"];
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
[myHandle seekToEndOfFile];
[myHandle writeData: data];
[myHandle closeFile];
// [data writeToFile:appFile atomically:YES];
// Show contents of Documents directory
NSLog(#"Documents directory: %#",
[fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
But in NSlog i don't see that there is my file. What is wrong?
If the files does not exist then [NSFileHandle fileHandleForUpdatingAtPath:] will return nil (see the docs).
Therefore check that before attempting to open the file and create it if necessary:
NSFileManager *fileMan = [NSFileManager defaultManager];
if (![fileMan fileExistsAtPath:appFile])
{
[fileMan createFileAtPath:appFile contents:nil attributes:nil];
}
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
// etc.
And add more error-checking all round.

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 copy of database in iPhone

Can any one help me for:
How can we create copy of database?
How can we open that database in iPhone?
How can we create folder in our application path?
How can we copy folder with files in our application path?
"For Creating the copy of Database..."
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSString *finalPath = [documentPath stringByAppendingPathComponent:#"test.sqlite"];
success = [fileManager fileExistsAtPath:finalPath];
if(success)
{
NSLog(#"Database Already Created.");
return;
}
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"test.sqlite"];
success = [fileManager copyItemAtPath:defaultPath toPath:finalPath error:&error];
if(success)
{
NSLog(#"Database Created Successfully.");
}
"For Open that Database..."
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSString *finalPath = [documentPath stringByAppendingPathComponent:#"test.sqlite"];
if(sqlite3_open([finalPath UTF8String], &database) != SQLITE_OK)
{
sqlite3_close(database);
NSLog(#"Error to Open Database :- %s",sqlite3_errmsg(database));
}
"For Creating Folder in Application Path"
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/FolderName"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
}
"For Copying The Files And Folder in Application"
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/FolderName"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
BOOL successs;
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Files/FolderName"];
successs = [[NSFileManager defaultManager] fileExistsAtPath:defaultPath];
if(successs)
{
NSLog(#"TRUE");
NSString *strFile = [NSString stringWithFormat:#"%#",dataPath];
NSLog(#"File :- '%#'",strFile);
[fileManager copyItemAtPath:defaultPath toPath:strFile error:&error];
}
else
NSLog(#"FALSE");
}

create a directory in the 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];