I have something like this in my code
if(![[NSFileManager defaultManager] createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil]) {
HTTPLogError(#"Could not create directory at path: %#", uploadDirPath);
}
The contents of uploadDirPath is this :
/Users/UserJ/Library/Developer/CoreSimulator/Devices/535C67AB-F932-417B-8CC3-9A813F4F402C/data/Containers/Data/Application/347FA1B2-F790-46A6-B0D6-B638CF2F43F0/Music/
The above code works fine in the simulator but when I run it in my phone it gets into the condition saying it cant create the folder.
The content of the string when it shows up on my phone is
/var/mobile/Containers/Data/Application/3E115818-0619-46B0-BD13-BD35EFDF50E3/Music/
Any suggestions on why it cant create the folder on my phone ?
Update:
This is the code that comes before
NSArray* dirPaths = NSSearchPathForDirectoriesInDomains(NSMusicDirectory, NSUserDomainMask, YES);
NSString* MusicDir = [dirPaths objectAtIndex:0];
//------
MultipartMessageHeaderField* disposition = [header.fields objectForKey:#"Content-Disposition"];
NSString* filename = [[disposition.params objectForKey:#"filename"] lastPathComponent];
//--------
if ( (nil == filename) || [filename isEqualToString: #""] ) {
// it's either not a file part, or
// an empty form sent. we won't handle it.
return;
}
//NSString* uploadDirPath = [[config documentRoot] stringByAppendingPathComponent:#"upload"];
NSString* uploadDirPath = [MusicDir stringByAppendingString:#"/"];
BOOL isDir = YES;
if (![[NSFileManager defaultManager]fileExistsAtPath:uploadDirPath isDirectory:&isDir ]) {
[[NSFileManager defaultManager]createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
}
NSString* filePath = [uploadDirPath stringByAppendingPathComponent: filename];
if( [[NSFileManager defaultManager] fileExistsAtPath:filePath] )
{
//Delete this file if it exists
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}
I noticed that the array when run on Iphone is empty but when it runs on simulator its fine
NSArray* dirPaths = NSSearchPathForDirectoriesInDomains(NSMusicDirectory, NSUserDomainMask, YES);
I believe since application in iOS device runs in sandbox manner, AppData folder structure is predefined. Please try creating your Music directory inside Documents directory and it should work:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirPath = paths.firstObject;
NSString *uploadDirPath = [documentsDirPath stringByAppendingPathComponent:#"Music"];
if (![[NSFileManager defaultManager] createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil]) {
HTTPLogError(#"Could not create directory at path: %#", uploadDirPath);
}
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 have created a directory inside my project using this code
NSError * error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/createDirectory1"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
NSLog(#"Create a new Dir");
}
else
{
NSLog(#"Dir already exist");
}
now I want to check whether the directory exist or not? how can I get that through objective c code ?
NSString *docPath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath=[NSString stringWithFormat:#"%#/createDirectory1", docPath];
BOOL fileExists=[[NSFileManager defaultManager] fileExistsAtPath:filePath];
if (!fileExists)
{
}
else
{
// Your Code
}
firstly,you should get the project path .you can do it like the codes bellow
NSString *getProjectPath(){
NSString *projectPath = [NSString stringWithFormat:#"%s,__FILE__]; // your project path may have some same prefix to the macro __FILE__.
// do something
return projectPath;
}
then you use
[[NSFileManager defaultManager] fileExistsAtPath:dataPath] check if it exist
BOOL fileOrDirectoryExists = [[NSFileManager defaultManager] fileExistsAtPath:dataPath];
fileExistsAtPath:dataPath method returns a Boolean value that indicates whether a file or directory exists at a specified path. you are already doing it, as remus said.
I am creating a directory inside my application.Is there a code to view the contents of the directory in xcode. For example in android you can create a custom directory and view its contents using a file manager application. Can the similar procedure be done in apple?
Here is the code which i use to create a directory?
bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
fileManager = [NSFileManager defaultManager];
myImageDirectory = [fileManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask];
if ([myImageDirectory count] == 1){
NSLog(#"myImageDirectoryIs already present directory is already present");
}else{
directoryPath = [[myImageDirectory objectAtIndex:0] URLByAppendingPathComponent:bundleIdentifier];
NSLog(#"myImageDirectory directory name = %#",[directoryPath absoluteString]);
NSError *theError = nil;
if (![fileManager createDirectoryAtURL:directoryPath withIntermediateDirectories:NO attributes:nil error:&theError]){
NSLog(#"didnt write image data");
}else{
imagePath = [[directoryPath absoluteString] stringByAppendingPathComponent:[NSString stringWithFormat:#"/%#_%#_%#_image.jpg",dIdNo,iIdNo,[self currentDateandTime]]];
[imageData writeToFile:imagePath atomically:YES];
}
}
If your app is running in the simulator you'll need to use Finder. Go to the following directory:
/Users/<username>/Library/Application Support/iPhone Simulator/<iOS version>/Applications/<uuid>/Library/Application Support
If your app is running on the device you can use Xcode:
Connect the device
Choose menu option Window -> Organizer
Go to the Devices Tab
Click Applications under the device menu on the left
Pick your Application
The directory contents will be listed and you can optionally download everything.
try this...
to create a directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
to retrieve contents from directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *customDirectory = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
NSError * error;
NSArray *directoryContents = [[NSFileManager defaultManager]
contentsOfDirectoryAtPath:customDirectory error:&error];
for(NSString *strFile in directoryContents)
{
NSString *strVideoPath = [NSString stringWithFormat:#"%#/%#",customDirectory,strFile];
if([[strVideoPath pathExtension] isEqualToString:#"mp4"] || [[strVideoPath pathExtension] isEqualToString:#"mov"])
{
[urlArray addObject:strVideoPath];
}
}
you can get the contents of the directory(MYNewFolder) from below code:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"MYNewFolder"];
NSArray *filePathsArray = [[NSFileManager defaultManager]
subpathsOfDirectoryAtPath:stringPath
error:nil];
for ( NSString *apath in filePathsArray )
{
NSLog(#"inside the file path array=%d",apath);
}
Method
-(NSArray *) getObjectsInDirectory:(NSString *)directory {
NSFileManager * fm = [NSFileManager defaultManager];
NSError * error = nil;
NSArray * result = [fm contentsOfDirectoryAtPath:directory error:&error];
return result;
}
How-To
NSString * documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray * files = [self getobjectsInDirectory:documentsPath];
This code is used to get an array of the files within the documents directory.
Viewing the Files
NSLog(#"%#", files);
Check this class out, it allows you to simplify so many things in iOS: Atomic Class
I'm writing an app that needs to store some persistence information in file but i'm having trouble debugging the createFileAtPath:contents:attributes: function of NSFileManager, i have reduced the problem to the below piece of code.
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
NSString * fileName = #"newfile.txt";
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent: fileName];
NSLog(#"full path name: %#", filePath);
// check if file exists
if ([filemgr fileExistsAtPath: filePath] == YES){
NSLog(#"File exists");
}else {
NSLog (#"File not found, file will be created");
if (![filemgr createFileAtPath:filePath contents:nil attributes:nil]){
NSLog(#"Create file returned NO");
}
}
Since the function doesn't take an NSError object i'm having trouble finding out why exactly it is returning false.
From other examples i have seen here Write a file on iOS and here How to programmatically create an empty .m4a file of a certain length under iOS using CoreAudio on device? it should be ok to pass nil to both the contents and attributes parameters. I've tried specifying both parameters and receive the same result.
I'm thinking this may be a permissions issue but i'm unsure if the below code is the correct way to check permissions on a directory.
if ([filemgr isWritableFileAtPath:documentsDirectory] == YES){
NSLog (#"File is readable and writable");
}
// Following Code will create Directory in DocumentsDirectory
NSString *docDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *dirName = [docDir stringByAppendingPathComponent:#"MyDir"];
BOOL isDir
NSFileManager *fm = [NSFileManager defaultManager];
if(![fm fileExistsAtPath:dirName isDirectory:&isDir])
{
if([fm createDirectoryAtPath:dirName withIntermediateDirectories:YES attributes:nil error:nil])
NSLog(#"Directory Created");
else
NSLog(#"Directory Creation Failed");
}
else
NSLog(#"Directory Already Exist");
swift5
guard let docdir = NSSearchPathForDirectoriesInDomains(.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first else {
preconditionFailure()
}
let path = (docdir as NSString).appendingPathComponent(yourfilename + "." + yourfilenameExtension)
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;
}