- (NSURL *) applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
....
NSURL *folder = [[[Database sharedInstance] applicationDocumentsDirectory] URLByAppendingPathComponent:#"temp"];
BOOL isFolder;
NSLog(#"URL: %#", folder);
if ([[NSFileManager defaultManager] fileExistsAtPath:folder.absoluteString isDirectory:&isFolder] == NO)
{
NSLog(#"IsFolder: %d", isFolder);
[[NSFileManager defaultManager] createDirectoryAtURL:folder withIntermediateDirectories:YES attributes:nil error:&error];
if (error)
NSLog(#"Error: %#", error.localizedDescription);
}
I run this part of code twice.
I expect that the folder will be created, but every time I receive a log: "IsFolder: 7".
Why the folder wasn't created after the first run?
The problem was in folder.absoluteString.
It should be folder.path instead.
Please, replace folder.absoluteString to folder, your problem will be solved.
Follow step by step:
1) Get documents folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
2) Get documents folder and folder name
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"MyFolder"];
3) Check alerdy exists or not
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
NSError* error;
if( [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error])
else
{
NSLog(#"[%#] ERROR: attempting to write create MyFolder directory", [self class]);
NSAssert( FALSE, #"Failed to create directory maybe out of disk space?");
}
Related
I have a sqlite file that I am trying to store in Application Support Folder. I am using the following code to create the directory.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *applicationSupportDirectory = [paths firstObject];
NSError *err;
NSString *dataPath = [applicationSupportDirectory stringByAppendingPathComponent:#"/Email"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&err]; //Create folder
NSString *dataBasePath = [applicationSupportDirectory stringByAppendingString:#"/Email/Email.sqlite"];
This is the printed result when I NSLog dataBasePath
/var/mobile/Containers/Data/Application/8A40E5A9-EEE6-46EF-B71F-36C9A00D5996/Library/Application
Support/Email/Email.sqlite
Is this correct way of creating the directory to store my sql file in Application Support? I have to use Application Support so the user can't mess with it (I use file share so document directory is out of the question) and the OS shouldn't be able to mess with it either. I just need to be sure
It's close but not quite right. Don't put the / before Email. You want to pass YES to withIntermediateDirectories. And the final path should use dataPath and stringByAppendingPathComponent.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *applicationSupportDirectory = [paths firstObject];
NSString *dataPath = [applicationSupportDirectory stringByAppendingPathComponent:#"Email"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
NSError *err;
if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&err]) { //Create folder
NSLog(#"Unable to create folder at %#: %#", dataPath, err);
}
}
NSString *dataBasePath = [dataPath stringByAppendingPathComponent:#"Email.sqlite"];
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.
I am trying to copy a file from one folder to another folder in documents directory like this:
- (void)saveFile:(NSString *)folderPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"destination.png"];
NSError *error = nil;
NSString *srcPath = [folderPath stringByAppendingPathComponent:#"filename.png"];
BOOL success = [[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:documentsDirectory error:&error];
if (error)
{
NSLog(#"%#",error);
}
if (success == YES)
{
NSLog(#"Copied");
}
else
{
NSLog(#"Not Copied");
}
}
When i log error, it gives me the following message:
Error Domain=NSCocoaErrorDomain Code=516 "The operation couldn’t be completed. (Cocoa error 516.)" UserInfo=0x9d665a0 {NSUserStringVariant=(
Move
), NSFilePath=/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/BC37C9D7-7995-47C1-8131-2B07BADCBECB/Documents/foldername/B713320C-2CA0-4FD3-93F6-71D76B102B83/src.png, NSDestinationFilePath=/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/BC37C9D7-7995-47C1-8131-2B07BADCBECB/Documents, NSUnderlyingError=0x9d41c60 "The operation couldn’t be completed. File exists"}
Issue 1:
The issue occurred because, the directory already contains a file with same file name.
You should check whether the file exist in the folder or not like:
- (void)saveFile:(NSString *)folderPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"destination.png"];
NSError *error = nil;
NSString *srcPath = [folderPath stringByAppendingPathComponent:#"filename.png"];
if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
//removing file
if (![[NSFileManager defaultManager] removeItemAtPath:dataPath error:&error])
{
NSLog(#"Could not remove old files. Error:%#",error);
}
}
BOOL success = [[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:dataPath error:&error];
if (success == YES)
{
NSLog(#"Copied");
}
else
{
NSLog(#"Not Copied %#", error);
}
}
Issue 2:
You must provide a file name not a directory.
Replace:
BOOL success = [[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:documentsDirectory error:&error];
With:
BOOL success = [[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:dataPath error:&error];
copyItemAtPath: is giving error as that file is already exist in that location. So you should do this before you copy file.
if ([[NSFileManager defaultManager] fileExistsAtPath: srcPath])
[[NSFileManager defaultManager] removeItemAtPath: srcPath error:nil];
Replace this line:
BOOL success = [[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:documentsDirectory error:&error];
With:
BOOL success = [[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:dataPath error:&error];
I want to create a directory inside my applicationSupportDirectory. My understanding is that the applicationSupportDirectory does not allow users to see the data within. This is why I have chosen it. However, the code I am using below seems to fail and I am not sure why.
Can anyone tell me what I have done wrong? Thanks!
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *applicationDirectory = [paths objectAtIndex:0]; // Get directory
NSString *dataPath = [applicationDirectory stringByAppendingPathComponent:#"drawings"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
NSError* error;
if([[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error])
;// success
else
{
NSLog(#"Failed");
}
}
}
Try this one, it works for me.
NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES)[0];
NSString *folder = [documentsPath stringByAppendingPathComponent:#"foldername"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
if (![fileManager fileExistsAtPath:folder]){
[fileManager createDirectoryAtPath:folder
withIntermediateDirectories:YES
attributes:nil
error:&error];
}
NSString *directoryName = #"drawing";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *applicationDirectory = [paths objectAtIndex:0];
NSString *filePathAndDirectory = [applicationDirectory stringByAppendingPathComponent:directoryName];
NSError *error;
if (![[NSFileManager defaultManager] createDirectoryAtPath:filePathAndDirectory
withIntermediateDirectories:YES
attributes:nil
error:&error])
{
NSLog(#"Create directory error: %#", error);
}
Hope it will help you
To create Dirtectory
NSError *error;
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:#"Library/Application Support/directoryname"];
NSLog(#"%#",path);
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
// Set do not backup attribute to whole folder
}
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];