Renaming all files and directories in NSLibraryDirectory - ios

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];
}
}
}
}

Related

Sometime ERROR copy file from bundle to documents directory in iOS

I am trying to copy a file from my bundle to the documents directory in iOS with the following code.
code:
- (NSString*)getModuleHome{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[[paths objectAtIndex:0] stringByAppendingPathComponent:#"webapp" ]stringByAppendingPathComponent:#"modules"];
return path;
}
- (void)FirstLoad{
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:[self getModuleHome]]) {
//建立目录
[[NSFileManager defaultManager] createDirectoryAtPath:[self getModuleHome] withIntermediateDirectories:YES attributes:nil error:nil];
}
NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
BLYLogInfo(#"FirstLoad");
NSString *zipPath = [[NSBundle mainBundle] pathForResource:#"" ofType:#"zip"];
NSString *path = NSTemporaryDirectory();
NSString *dataPath = [path stringByAppendingPathComponent:#"modules.zip"];
if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
BLYLogInfo(#"fileExistsAtPath dataPath");
[[NSFileManager defaultManager] removeItemAtPath:dataPath error:&error];
}
if(![[NSFileManager defaultManager] copyItemAtPath:zipPath toPath:dataPath error:&error])
{
BLYLogError(#"Error copying files: %#", [error localizedDescription]);
[Bugly reportError:error];
}
BLYLogInfo(#"FirstLoad Unzip");
NSString *unZipPath = [path stringByAppendingPathComponent: #"modules"];
if ([[NSFileManager defaultManager] fileExistsAtPath:unZipPath]) {
[[NSFileManager defaultManager] removeItemAtPath:unZipPath error:&error];
}
[SSZipArchive unzipFileAtPath:dataPath toDestination:unZipPath];
BLYLogInfo(#"FirstLoad Copy");
NSString *destinationPath = [self getModuleHome];
BLYLogInfo(#"FirstLoad destinationPath:%#",destinationPath);
if ([[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) {
BLYLogWarn(#"FirstLoad removeItemAtPath");
[[NSFileManager defaultManager] removeItemAtPath:destinationPath error:&error];
}
if (![[NSFileManager defaultManager] copyItemAtPath:unZipPath toPath:destinationPath error:&error]) {
BLYLogError(#"FirstLoad Error copying files: %#", [error localizedDescription]);
[Bugly reportError:error];
NSLog(#"FirstLoad Clean");
[[NSFileManager defaultManager] removeItemAtPath:dataPath error:nil];
[[NSFileManager defaultManager] removeItemAtPath:unZipPath error:nil];
//加载出错
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView* view = [[UIAlertView alloc] initWithTitle:#"提示"
message:#"抱歉,资源加载失败,请关闭重试"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
[view show];
});
}
else{
BLYLogInfo(#"FirstLoad Clean");
[[NSFileManager defaultManager] removeItemAtPath:dataPath error:nil];
[[NSFileManager defaultManager] removeItemAtPath:unZipPath error:nil];
[userDef setObject:#"NO" forKey:#"UpdateFlag"];
[userDef synchronize];
[self FirstReload];
}
}
Attach Log:
User Data: NSErrorUserInfo: { NSDestinationFilePath =
"/var/mobile/Containers/Data/Application/3575F3DD-4DC7-4472-A3D0-D4FF86C40BEF/Documents/webapp/modules/ihub/img/cat.png";
NSFilePath =
"/private/var/mobile/Containers/Data/Application/3575F3DD-4DC7-4472-A3D0-D4FF86C40BEF/tmp/modules/ihub/img/cat.png";
NSSourceFilePathErrorKey =
"/private/var/mobile/Containers/Data/Application/3575F3DD-4DC7-4472-A3D0-D4FF86C40BEF/tmp/modules/ihub/img/cat.png";
NSUnderlyingError = "Error Domain=NSPOSIXErrorDomain Code=2 \"No such
file or directory\""; NSUserStringVariant = ( Copy ); }
The app has been released.
Most phones are normal.
Only some phones have this problem.
Each log file reported errors is not the same file not exist.
SAMPLE:
NSError(NSCocoaErrorDomain:4)The
file“contractpayment-detail.html”doesn’t exist。
NSError(NSCocoaErrorDomain:4)The file “vacating.png” doesn’t exist.
NSError(NSCocoaErrorDomain:4)The file “Mode.ts” doesn’t exist.
NSError(NSCocoaErrorDomain:4)The file “SystemCtrl.js” doesn’t exist.
"Why? How to fix it?"
plz try this code
//array of main bundle images
NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:#"admin_1454993109_restaurants_uploaded",
#"admin_1454993149_other_uploaded",
#"admin_1454993170_car_uploaded",
#"admin_1454993206_home_uploaded",
#"admin_1454993235_fashion_uploaded",
#"admin_1454993290_shirt_uploaded",
#"admin_1454993347_electronic_uploaded",
#"admin_1454993380_notes_uploaded", nil];
for (int i = 0; i < array.count; i++) {
// file URL in our bundle
NSURL *fileFromBundle = [[NSBundle mainBundle]URLForResource:[NSString stringWithFormat:#"%#",[array objectAtIndex:i]] withExtension:#"jpg"];
// Destination URL
NSString *path = [self MyImagesDocumentsDirectoryPath];
NSString *filePath = [NSString stringWithFormat:#"%#/%#.jpg",path,[array objectAtIndex:i]];
NSURL *destinationURL = [NSURL fileURLWithPath:filePath];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
// copy it over
[[NSFileManager defaultManager]copyItemAtURL:fileFromBundle toURL:destinationURL error:&error];
NSLog(#"%#",error);
}
}
- (NSString *)MyImagesDocumentsDirectoryPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
return dataPath;
}
here i am copying the images into MyFolder from Main bundle. you can give your zip files name and use this code.

Remove File with Space in Filename 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]);
}

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);
}

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);
}
}

How to get the list of directores in NSDocumentDirectory?

I have created some directories in NSDocumentDirectory as
if (![tbxCreateFolder.text isEqualToString:#""]) {
NSArray *arrPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryStr = [arrPaths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectoryStr stringByAppendingPathComponent:[NSString stringWithFormat:#"/%#",tbxCreateFolder.text]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
NSError* error;
if([[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]){
NSLog(#"success");
//Perfrom DB Insertation
}
else
{
NSLog(#"[%#] ERROR: attempting to write create MyFolder directory", [self class]);
NSAssert( FALSE, #"Failed to create directory maybe out of disk space?");
}
}
}
Now i want to get the list of directories that i have created in document folder but response is
NSArray *arrPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePathString = ([arrPaths count] > 0) ? [arrPaths objectAtIndex:0] : nil;
NSLog(#"dirContents %#",basePathString);
Response is:
/Users/amir/Library/Application Support/iPhone Simulator/6.1/Applications/7003E8D5-CCBB-4E54-896B-F4BD2F4D2CB1/Documents
Here is the code:
NSString *documentDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// create directory named "test"
[[NSFileManager defaultManager] createDirectoryAtPath:[documentDirPath stringByAppendingPathComponent:#"test"] withIntermediateDirectories:YES attributes:nil error:nil];
// retrieved all directories
NSLog(#"%#", [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirPath error:nil]);
NSArray *paths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirPath error:nil];
BOOL isDir = NO;
for (NSString *path in paths) {
if ([fileManager fileExistsAtPath:path isDirectory:&isDir] && isDir) {
// path is directory
}
}
You could always enumerate the contents of the top level directory using -fileExistsAtPath:isDirectory: like this:
NSFileManager *sharedFileManager = [NSFileManager defaultManager];
NSDirectoryEnumerator *files = [sharedFileManager enumeratorAtPath:yourPath];
for (NSString *path in files) {
BOOL isDirectory = NO;
[sharedFileManager fileExistsAtPath:path isDirectory:&isDirectory];
if (isDirectory) {
// you found a directory, so do what you will with it
}
}
You can do this with few simple lines of code
NSString *documentDirectoryPath = // Initialize with Documents path
BOOL isDir = NO;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *files = [fileManager contentsOfDirectoryAtPath:documentDirectoryPath error:NULL];
NSMutableArray *directoriesPaths = [NSMutableArray array];
for (NSString *filePath in files) {
if ([fileManager fileExistsAtPath:filePath isDirectory:&isDir] && isDir) {
[directoriesPaths addObject:filePath];
}
}
NSLog(#"directories %#", directoriesPaths);
try this,
NSArray *arrPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *strFilePath = [[arrPath objectAtIndex:0]
[[NSFileManager defaultManager] createDirectoryAtPath:[strFilePath stringByAppendingPathComponent:#"Sample"] withIntermediateDirectories:YES attributes:nil error:nil];

Resources