Remove File with Space in Filename ios - ios

I want to remove an image for Documents Directory. The image has this 2016-06-08 12:24:55.897image.jpg kind of naming convention.
Code Snippet
-(void) removeImageAtPath:(NSString *) filePath{
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager removeItemAtPath:filePath error:&error];
if (success) {
NSLog(#"Image Successfully Deleted");
}
else{
NSLog(#"Could not delete file -:%# ",[error localizedDescription]);
}
}
Error Code
NSCocoaErrorDomain Code = 4
I know the error comes when the file is not found. Which is happening because of the naming convention i have used.
I cannot change the convention. Is there any way to still remove the file.

this code remove directly file name
- (void)removeImage:(NSString *)filename
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:filename];
NSError *error;
BOOL success = [fileManager removeItemAtPath:filePath error:&error];
if (success) {
UIAlertView *removedSuccessFullyAlert = [[UIAlertView alloc] initWithTitle:#"Congratulations:" message:#"Successfully removed" delegate:self cancelButtonTitle:#"Close" otherButtonTitles:nil];
[removedSuccessFullyAlert show];
}
else
{
NSLog(#"Could not delete file -:%# ",[error localizedDescription]);
}
}
other wise use this code
NSError *error;
if ([[NSFileManager defaultManager] isDeletableFileAtPath:path]) {
BOOL success = [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
if (!success) {
NSLog(#"Error removing file at path: %#", error.localizedDescription);
}
}
can you please try this code
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
BOOL fileExists = [fileManager fileExistsAtPath:path];
NSLog(#"Path to file: %#", path);
NSLog(#"File exists: %d", fileExists);
NSLog(#"Is deletable file at path: %d", [fileManager isDeletableFileAtPath:path]);
if (fileExists)
{
BOOL success = [fileManager removeItemAtPath:path error:&error];
if (!success) NSLog(#"Error: %#", [error localizedDescription]);
}

Related

NSData:writeToFile returning error "File doesn't exist"

I'm currently using the following code to write a NSData in a subfolder of the documents folder.
NSData* dataToSave=...;
NSFileManager* fileManager = [NSFileManager defaultManager];
NSString* documentsDir=[
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
objectAtIndex:0];
NSString* desiredFolder=[documentsDir stringByAppendingPathComponent:#"MySubfolder"];
BOOL isDir;
if (![fileManager fileExistsAtPath:desiredFolder isDirectory:&isDir]&&!isDir)
{
NSError* error;
[fileManager createDirectoryAtPath:desiredFolder
withIntermediateDirectories:NO attributes:nil error:&error];
if (error) {
NSLog(#"Error%#", error.localizedDescription);
}
}
NSString* desiredFile=[desiredFolder stringByAppendingPathComponent:#"mfile.jpeg"];
if (![dataToSave writeToFile:desiredFile options:NSDataWritingAtomic error:&error])
{
NSLog(#"Error %#",error.localizedDescription);
return NO;
}
It was working until I tested this config in "release mode" . There the NSData:writeToFile started to return NO, with the error: The file 'myfile.jpeg´ doesn't exist.
Where is the problem?
Thanks
Thanks to #mbi I found the answer.
The problem is when validating the existence of the parent folder:
if (![fileManager fileExistsAtPath:desiredFolder isDirectory:&isDir]&&!isDir)
This is incorrect. Since the isDirectory param is unsafe isDir can be true even if the result of the method is NO. So the correct way to evaluate is just:
if (![fileManager fileExistsAtPath:desiredFolder isDirectory:nil])
Or if you want to handle the case where the file exists but is not a directory:
if (![fileManager fileExistsAtPath:desiredFolder isDirectory:&isDir]){
...
}else if(!isDir) {
...
}
Try this method.
if (![dataToSave writeToFile:desiredFile atomically:YES])
{
NSLog(#"Error writing to file : %#",desiredFile);
return NO;
}

Get name of subdirectories within Reference Folder ios

I need to ask is there is any way to fetch the name or the path of the folders/subdirectories with in the Reference folder.
I have figured out the way to get the path of the files(.png) in Array within a reference folder but I am curious that is there any way to find the folder also ???
You can try like this where you can pass your directory name as documentsURL
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = [[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
NSURL *documentsURL = [paths lastObject];
NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:documentsURL includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:^BOOL(NSURL *url, NSError *error)
{
if (error) {
NSLog(#"[Error] %# (%#)", error, url);
return NO;
}
return YES;
}];
for (NSString* file in enumerator) {
NSLog(#"File %#",file);
}

Downloading from iCloud

I have iCloud support in my application. and I save database in iCloud successfully. But when I try to download this database file by using bellow code
NSFileManager *fm = [NSFileManager defaultManager];
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (ubiq == nil) {
return;
}
NSError *theError = nil;
NSURL *url = [[ubiq URLByAppendingPathComponent:#"Documents" isDirectory:true] URLByAppendingPathComponent:fileName];
bool started = [fm startDownloadingUbiquitousItemAtURL:url error:&theError];
NSLog(#"started download for %# %d", fileName, started);
if (theError != nil) {
NSLog(#"iCloud error: %#", [theError localizedDescription]);
}
else
{
}
Downloading start successfully but I don't know where it will be download OR what will be the destination path. How can I save this file to local directory of app. Please help

Renaming all files and directories in NSLibraryDirectory

How can I rename all files and directories to lower case in NSLibraryDirectory\myFolder?
I found that I can to use:
[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:[oldPath lowercaseString] error:&error];
to renaming directories.
NSArray *directoryContent = [fileManager contentsOfDirectoryAtPath:path error:nil];
To getting array with directory contents but how I can check if directoryContent[0] is directory or file.
You could use this to check if a NSUrl is a directory or file:
for (NSURL *item in directoryContent) {
NSString *path = [item path];
BOOL isDir;
if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]) {
if (isDir) {
NSLog(#"%# is a directory", path);
} else {
NSLog(#"%# is a file", path);
}
} else {
NSLog(#"%# does not exist", path);
}
}
UPDATE:
To rename all contents of your directory you could use this:
NSArray *directoryContent = [fileManager contentsOfDirectoryAtPath:path error:nil];
BOOL isDir;
for (NSURL *item in directoryContent) {
if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]) {
if (isDir) {
// create a new directory with lowercase name,
// move contents of old directory to the new one
// then delete the old directory
} else {
[[NSFileManager defaultManager] moveItemAtPath:path toPath:[path lowercaseString] error:&error];
}
}
}
//Call [self purgeDirectory:__NSLibraryDirectoryPath];
+(void)purgeDirectory:(NSString *)directoryPath __deprecated_msg("For debug purposes only") {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *directoryContent = [fileManager contentsOfDirectoryAtPath:directoryPath error:&error];
for (NSString *itemPath in directoryContent) {
BOOL isDir;
if ([[NSFileManager defaultManager] fileExistsAtPath:itemPath isDirectory:&isDir]) {
if (isDir) {
[self purgeDirectory:itemPath];//subdirectory
} else {
[[NSFileManager defaultManager] removeItemAtPath:itemPath error:&error];
}
}
}
}

iCloud Folder Creating and Saving in iOS

I need to create Folder in Cloud and save my .txt Text File into that Folder.
So i created folder with following codes in AppDelegate
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSError *error = nil;
if(ubiq)
{
NSFileManager *fm = [NSFileManager defaultManager];
NSURL *rootURL = [fm URLForUbiquityContainerIdentifier:nil];
NSURL *newFolder = [NSURL URLWithString:#"Notes" relativeToURL:rootURL];
[fm createDirectoryAtURL:newFolder withIntermediateDirectories:YES attributes:nil error:&error];
if(error)
{
NSLog(#"Error");
}
else
{
NSLog(#"NO Error");
}
}
After i test it , It show No Error.
So i assumed that it created Notes Folder in iCloud.
However when i save my text document into that folder with following codes , it showing error and not save.
NSString *file = [NSString stringWithFormat:#"%#.txt",fileName];
NSURL *ubiq = [[NSFileManager defaultManager]
URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage =
[[[ubiq URLByAppendingPathComponent:#"Documents"] URLByAppendingPathComponent:#"Notes"]
URLByAppendingPathComponent:file];
Note *doc = [[Note alloc] initWithFileURL:ubiquitousPackage];
[doc saveToURL:[doc fileURL] forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (!success)
{
NSLog(#"Error");
}
else
{
doc.noteContent = self.txtView.text;
[doc updateChangeCount:UIDocumentChangeDone];
}
}];
And the error message is
Foundation called mkdir("/private/var/mobile/Library/Mobile Documents/35QNLTQU29~com~myapp~iCloudTest/Documents/Notes/(A Document Being Saved By iCloudTest)"), it didn't return 0, and errno was set to 2.
How can i solve it?

Resources