How to rename files/folders from document folder programmatically in iOS - ios

I am working on functionality to save video files in document folder of application in iOS.
How to rename some files programmatically?

try this code :
NSError * err = NULL;
NSFileManager * fm = [[NSFileManager alloc] init];
BOOL result = [fm moveItemAtPath:#"/tmp/test.tt" toPath:#"/tmp/dstpath.tt" error:&err];
if(!result)
NSLog(#"Error: %#", err);
other wise use this method to rename file
- (void)renameFileWithName:(NSString *)srcName toName:(NSString *)dstName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePathSrc = [documentsDirectory stringByAppendingPathComponent:srcName];
NSString *filePathDst = [documentsDirectory stringByAppendingPathComponent:dstName];
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePathSrc]) {
NSError *error = nil;
[manager moveItemAtPath:filePathSrc toPath:filePathDst error:&error];
if (error) {
NSLog(#"There is an Error: %#", error);
}
} else {
NSLog(#"File %# doesn't exists", srcName);
}
}

There is no Direct API to rename the file . Though when you move the file from one place to another place, if that file in destination path not exists then iOS will create the file in the given name. For file you can just give the New name of your file, how it should be displayed/referenced.
you could check this answer. Good luck!

Related

Replacing UISaveVideoAtPathToSavedPhotosAlbum #selector videoSaved function

Xcode 7
Swift 2
Objective C
I have changed some Objective C code, and I do not know Objective C syntax at all. I have replaced the following code that was saving videos to the camera roll:
if ( UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(newPath))
// Copy it to the camera roll.
UISaveVideoAtPathToSavedPhotosAlbum(newPath, self, #selector(videoSaved:didFinishSavingWithError:contextInfo:), (__bridge void *)(AvailableVideos[0]));
else
{
[self ErrorOnDownloadOrSave];
return;
}
With code that is saving the video to the Data Container Document Directory of my app:
NSString *tempFilePath = [downloadURL path];
NSError * error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/Videos"];
//NSString *newPath = [[tempFilePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:AvailableVideos[0]];
NSString *newPath = [dataPath stringByAppendingPathComponent:AvailableVideos[0]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:dataPath])
[fileManager createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
//copying temp video to Documents Directory
if ([fileManager fileExistsAtPath:newPath] == YES)
[fileManager removeItemAtPath:newPath error:&error];
[fileManager copyItemAtPath:tempFilePath toPath:newPath error:&error];
In the Objective C code that is saving to the iOS Camera Roll there is an Objective C "function" that is called when the "videoSaved" event is complete:
-(void)videoSaved:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
//implementation
}
I need to figure out how to call this "function", "videoSaved" after this code:
//copying temp video to Documents Directory
if ([fileManager fileExistsAtPath:newPath] == YES)
[fileManager removeItemAtPath:newPath error:&error];
[fileManager copyItemAtPath:tempFilePath toPath:newPath error:&error];
I realize the videoSaved function is a special signature for UISaveVideoAtPathToSavedPhotosAlbum but I am just so unfamiliar with Objective C that I do not know how to write a new function that I can call, and pass the my error object and maintain the implementation of videoSaved.
According to NSFileManager documentation, the method copyItemAtPath returns BOOL.
YES if the item was copied successfully or the file manager’s delegate stopped the operation deliberately. Returns NO if an error occurred.
So you can do something like :
if ([fileManager copyItemAtPath:tempFilePath toPath:newPath error:&error]) {
//saved
NSLog(#"video saved");
} else {
//error
NSLog(#"error occured : %#", error);
}

How to get List of files/Upload/rename/write/read files in ios device programmatically?

I am creating an app in which user will have to upload the files and images like xls, pdf, txt, jpg, png etc. I want to show the user all the files present in his iOS device please help me any one.
First of all you should read NSFileManager concept in Apple Documentation then automatically you should know how to do this::
what you can access is within your app only, nothing more –
Can you please see the following code . i hope it will be helpful to you
(1). #pragma mark
#pragma mark -- list all the files exists in Document Folder in our Sandbox.
- (void)listAllLocalFiles{
// Fetch directory path of document for local application.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// NSFileManager is the manager organize all the files on device.
NSFileManager *manager = [NSFileManager defaultManager];
// This function will return all of the files' Name as an array of NSString.
NSArray *files = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
// Log the Path of document directory.
NSLog(#"Directory: %#", documentsDirectory);
// For each file, log the name of it.
for (NSString *file in files) {
NSLog(#"File at: %#", file);
}
}
(2). #pragma mark
#pragma mark -- Create a File in the Document Folder.
- (void)createFileWithName:(NSString *)fileName{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSFileManager *manager = [NSFileManager defaultManager];
// 1st, This funcion could allow you to create a file with initial contents.
// 2nd, You could specify the attributes of values for the owner, group, and permissions.
// Here we use nil, which means we use default values for these attibutes.
// 3rd, it will return YES if NSFileManager create it successfully or it exists already.
if ([manager createFileAtPath:filePath contents:nil attributes:nil]) {
NSLog(#"Created the File Successfully.");
} else {
NSLog(#"Failed to Create the File");
}
}
(3). #pragma mark
#pragma mark -- Delete a File in the Document Folder.
- (void)deleteFileWithName:(NSString *)fileName{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// Have the absolute path of file named fileName by joining the document path with fileName, separated by path separator.
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSFileManager *manager = [NSFileManager defaultManager];
// Need to check if the to be deleted file exists.
if ([manager fileExistsAtPath:filePath]) {
NSError *error = nil;
// This function also returnsYES if the item was removed successfully or if path was nil.
// Returns NO if an error occurred.
[manager removeItemAtPath:filePath error:&error];
if (error) {
NSLog(#"There is an Error: %#", error);
}
} else {
NSLog(#"File %# doesn't exists", fileName);
}
}
(4). #pragma mark
#pragma mark -- Rename a File in the Document Folder.
- (void)renameFileWithName:(NSString *)srcName toName:(NSString *)dstName{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePathSrc = [documentsDirectory stringByAppendingPathComponent:srcName];
NSString *filePathDst = [documentsDirectory stringByAppendingPathComponent:dstName];
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePathSrc]) {
NSError *error = nil;
[manager moveItemAtPath:filePathSrc toPath:filePathDst error:&error];
if (error) {
NSLog(#"There is an Error: %#", error);
}
} else {
NSLog(#"File %# doesn't exists", srcName);
}
}
(5).#pragma mark
#pragma mark -- Read a File in the Document Folder.
/* This function read content from the file named fileName.
*/
- (void)readFileWithName:(NSString *)fileName{
// Fetch directory path of document for local application.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// Have the absolute path of file named fileName by joining the document path with fileName, separated by path separator.
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
// NSFileManager is the manager organize all the files on device.
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]) {
// Start to Read.
NSError *error = nil;
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSStringEncodingConversionAllowLossy error:&error];
NSLog(#"File Content: %#", content);
if (error) {
NSLog(#"There is an Error: %#", error);
}
} else {
NSLog(#"File %# doesn't exists", fileName);
}
}
(6). #pragma mark
#pragma mark -- Write a File in the Document Folder.
/* This function Write "content" to the file named fileName.
*/
- (void)writeString:(NSString *)content toFile:(NSString *)fileName{
// Fetch directory path of document for local application.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// Have the absolute path of file named fileName by joining the document path with fileName, separated by path separator.
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
// NSFileManager is the manager organize all the files on device.
NSFileManager *manager = [NSFileManager defaultManager];
// Check if the file named fileName exists.
if ([manager fileExistsAtPath:filePath]) {
NSError *error = nil;
// Since [writeToFile: atomically: encoding: error:] will overwrite all the existing contents in the file, you could keep the content temperatorily, then append content to it, and assign it back to content.
// To use it, simply uncomment it.
// NSString *tmp = [[NSString alloc] initWithContentsOfFile:fileName usedEncoding:NSStringEncodingConversionAllowLossy error:nil];
// if (tmp) {
// content = [tmp stringByAppendingString:content];
// }
// Write NSString content to the file.
[content writeToFile:filePath atomically:YES encoding:NSStringEncodingConversionAllowLossy error:&error];
// If error happens, log it.
if (error) {
NSLog(#"There is an Error: %#", error);
}
} else {
// If the file doesn't exists, log it.
NSLog(#"File %# doesn't exists", fileName);
}
// This function could also be written without NSFileManager checking on the existence of file,
// since the system will atomatically create it for you if it doesn't exist.
}
What you want to is not possible in iOS. An application you create only has access to files in it's Documents folder.
There is no "all files from the phone" notion, each application manages it's own files. The only way you can interact with other applications is through a public API provided by the application developers.
If you want to get all the files inside your Documents directory you can get the path this way:
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [searchPaths objectAtIndex:0];
You also have access to the user's photo library with which you can interact using ALAssets (up to iOS7) or PHAssets (iOS 8 and up).
Hope this helps.

how to find subfolder in an existing folder in iOS

My folder contains only one sub-folder, and I don't know sub-folder's name. This sub-folder contains a html file, and once again I don't know the html file's name.
My question is how I can get full path of this file by using
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:filename];
//- access sub-folder?
//- access html file?
EDITED:
I wrote a method to return the only one sub-folder as follow:
+ (NSString*) get1stSubFolder:(NSString*)folder
{
NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:folder];
//- no recursive
[directoryEnumerator skipDescendents];
NSString* file;
while (file = [directoryEnumerator nextObject])
{
BOOL isDirectory = NO;
BOOL subFileExists = [[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDirectory];
if (subFileExists && !isDirectory) {
return file;
}
}
return nil;
}
I always get nil as result. Do you know where was I wrong at?
Use NSDirectoryEnumerator. It should help you.
Use NSDirectoryEnumerator like this.
NSURL *documentsDirectoryURL = [NSURL URLWithString:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] ];
///If the folder you want to browse for subfolders is NSDocumentDirectory.
NSArray *keys = [NSArray arrayWithObject:NSURLIsDirectoryKey];
NSDirectoryEnumerator *enumerator = [[[NSFileManager alloc] init]
enumeratorAtURL:documentsDirectoryURL
includingPropertiesForKeys:keys
options:0
errorHandler:^(NSURL *url, NSError *error) {
return YES;
}];
for (NSURL *url in enumerator) {
NSError *error;
NSNumber *isDirectory = nil;
if (! [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) {
NSLog(#"Error %#",error);
}
else if ([isDirectory boolValue]) {
NSLog(#"Folder URL: %#",url);
}else{
NSLog(#"File URL: %#",url);
}
}

IOS: delete a file in a directory

In my app I download a pdf file with an ASiHttpRequest and I have these instructions:
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[currentDownload setDownloadDestinationPath:[documentsDirectory stringByAppendingPathComponent:#"file.pdf"]];
it work fine at first time, and I can open this file.pdf, but when I download a second time this pdf, it seems that it not replace the file but do a merge.
before I do this, but it doesn't work where is the problem, or what's the best way to delete this file.pdf from its path?
- (void) removeFile{
NSString *extension = #"pdf";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPDF = [paths objectAtIndex:0];
NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectoryPDF error:NULL];
NSEnumerator *e = [contents objectEnumerator];
NSString *filename;
while ((filename = [e nextObject])) {
if ([[filename pathExtension] isEqualToString:extension]) {
[fileManager removeItemAtPath:[documentsDirectoryPDF stringByAppendingPathComponent:filename] error:NULL];
}
}
}
EDIT
now I use this method
- (void) removeFile{
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0]stringByAppendingString:#"/file.pdf"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSLog(#"Documents directory before: %#", [fileManager contentsOfDirectoryAtPath:[paths objectAtIndex:0] error:&error]);
if([fileManager fileExistsAtPath:path] == YES)
{
NSLog(#"file exist and I delete it");
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:path error:&error];
NSLog(#"error:%#", error);
}
NSLog(#"Documents directory after: %#", [fileManager contentsOfDirectoryAtPath:[paths objectAtIndex:0] error:&error]);
}
this method recognize that in directory there is "file.pdf" in NSLog
NSLog(#"Documents directory before: %#", [fileManager contentsOfDirectoryAtPath:[paths objectAtIndex:0] error:&error]);
but it crash after
"NSLog(#"file exist and I delete it");"
and I have only a "lldb" in consolle.
I use this method to delete pdf files from a local cache, with a few modifications you can adapt it to your necessities
- (void)removePDFFiles
{
NSFileManager *fileMngr = [NSFileManager defaultManager];
NSArray *cacheFiles = [fileMngr contentsOfDirectoryAtPath:[self cacheDirectory]
error:nil];
for (NSString *filename in cacheFiles) {
if ([[[filename pathExtension] lowercaseString] isEqualToString:#"pdf"]) {
[fileMngr removeItemAtPath:[NSString stringWithFormat:#"%#/%#", [self cacheDirectory], filename] error:nil];
}
}
}
Most probably you don't remove the file before downloading a new one and ASIHttpRequest sees that there's already a file with the same name and appends data to it instead of replacing the file. I'm not sure about the PDF format, but that shouldn't normally result in a merged readable file. In any case, first you need to use the error mechanism that the filemanager class offers you. Is bad to pass NULL. Very bad. So, create a NSError object and pass it to the contentsOfDirectoryAtPath and removeItemAtPath methods, then check the error, be sure the operations are done successfully. After that, you may want to check the extension upper case as well, as Unix based systems are case sensitive (although the simulator is not, the device is) and a example.PDF file will not get deleted based on your code.
Try the following:
-(BOOL) removePDF
{
BOOL removeStatus = NO;
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString* fileName = #"file.pdf"; //your file here..
NSString* filePath = [NSString stringWithFormat:#"%#/%#", docsDir, fileName];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath] == YES)
{
removeStatus = [[NSFileManager defaultManager] removeItemAtPath:filePath];
}
return removeStatus;
}

How to delete a file from iTunes file sharing folder iOS

I have no problem with getting the path of the files that are located in the iTunes file sharing folder.. What I want is to delete them completely when the delete button is hit..
One more question.. is it possible to distinguish the file extension when delete button is hit? for example if it's an avi file, then alert user that he is about to delete a movie?
Thanks...
Thanks to Yannik L. Its now working.. I was just wondering one more thing.. How can I delete files with non-english charachers..?
The iTunesFileSharing folder is simply the document folder. You can retrieve the path by executing this code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folderPath = [paths objectAtIndex:0];
Then you can run through the files available into the document folder and test their extension to check if they are AVI files:
- (BOOL)existsMovieFilesAtPath:(NSString *)folderPath
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *contents = [fileManager contentsOfDirectoryAtPath:folderPath error:&error];
if (error == nil)
{
for (NSString *contentPath in contents)
{
NSString *fileExt = [contentPath pathExtension];
// If the current file is an AVI file
if ([fileExt isEqualToString:#"avi"])
{
return YES;
}
}
}
return NO;
}
And to delete the files you can make the same things:
- (BOOL)deleteFilesAtPath:(NSString *)folderPath
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *contents = [fileManager contentsOfDirectoryAtPath:folderPath error:&error];
if (error == nil)
{
for (NSString *contentPath in contents)
{
[fileManager removeItemAtPath:contentPath error:NULL];
}
}
return NO;
}

Resources