I was trying to create a CSV file using xcode but I can't seem to find the file anywhere after creation.
One solution I found was going into products folder itself but it isn't there.
Another solution that didn't work: Window-> Devices-> look at the installed apps of the devices but the container is empty.
Here is my code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *root = [documentsDir stringByAppendingPathComponent:#"test.csv"];
// Append file here
temp = [NSString stringWithFormat:#"%.0f", (float)*samples];
if (![[NSFileManager defaultManager] fileExistsAtPath:root]) {
[[NSFileManager defaultManager] createFileAtPath: root contents:nil attributes:nil];
NSLog(#"Route created");
}
NSError *error = nil;
NSLog(#"%#", root);
BOOL success = [temp writeToFile:root atomically:YES encoding:NSUTF8StringEncoding error:&error];
if(!success){
NSLog(#"fail to write to csv file");
}
It always is successful, but yet I can't find the file, also the file also seem to exists as it does not enter the if(fileExistsAtPath) after the first time.
The root directory is : /var/mobile/Containers/Data/Application/DDA4F37D-8D61-43F9-809C-31B09852B77F/Documents/test.csv
Edit: to make it clearer, I'm trying to retrieve it via xcode. Through finder so that I can get the csv file.
Any help is appreciated.
Related
I dont know about how to open NSFileManager.
How to open NSFileManager in iPhone and upload document from NSFileManager please suggest any easy way.
How can open it and upload the document and also get the path for saved file.
Where I can find file physically.(Any location).
::EDIT::
I started coding in that year. so, i don't know about basic of NSFileManager.
Show contents:
NSLog(#"Documents directory: %#", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
Get all files
//get an instance of the File Manager
NSFileManager *fileManager = [NSFileManager defaultManager];
//we'll list file in the temporary directory
NSString * strPath = NSTemporaryDirectory();
//we'll need NSURL for the File Manager
NSURL *tempDirURL = [NSURL fileURLWithPath:strPath];
//An array of NSURL object representing the path to the file
//using the flag NSDirectoryEnumerationSkipsHiddenFiles to skip hidden files
NSArray *directoryList = [fileManager contentsOfDirectoryAtURL:tempDirURL
includingPropertiesForKeys:nil
options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
Reference:http://www.ios-developer.net/iphone-ipad-programmer/development/file-saving-and-loading/using-the-document-directory-to-store-files
http://nshipster.com/nsfilemanager/
An iPhone's documents directory is used for saving data. We can save some personal data like as file, image, video etc. The document's directory's data will remain in the iPhone's memory until the application is forcibly terminated.
Let's see an example of how to store some images & retrieve those images later in an iPhone.
// For saving the images in the Document's Directory
-(void)saveImagesInIPhone:(NSData*)imageData withName:(NSString*)imageName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//Get the docs directory
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *folderPath = [documentsDirectoryPath stringByAppendingPathComponent:#"IconImages"]; // subDirectory
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath])
[[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:NOattributes:nil error:nil];
//Add the FileName to FilePath
NSString *filePath = [folderPath stringByAppendingPathComponent:[iconName stringByAppendingFormat:#"%#",#".png"]];
//Write the file to documents directory
[imageData writeToFile:filePath atomically:YES];
}
Result:- /var/mobile/Applications/20F869FD-5C61-4900-8CFE-830907731EC9/Documents/Designer0.png
///To retrieve the images from the document Directory
-(UIImage*)retrieveImageFromPhone:(NSString*)fileNamewhichtoretrieve
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//Get the docs directory
NSString *documentsPath = [paths objectAtIndex:0];
NSString *folderPath = [documentsPath stringByAppendingPathComponent:#"IconImages"]; // subDirectory
NSString *filePath = [folderPath stringByAppendingPathComponent:
[fileNamewhichtoretrieve stringByAppendingFormat:
#"%#",#".png"]];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
return [[UIImage alloc] initWithContentsOfFile:filePath];
else
return nil;
}
result :- /var/mobile/Applications/20F869FD-5C61-4900-8CFE-830907731EC9/Documents/Designer0.png
You can get Directory Path like this..
-(NSString *)getDBPath
{
//Searching a standard documents using NSSearchPathForDirectoriesInDomains
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [paths objectAtIndex:0];
NSLog(#"I am in --> getDBPath==%#",paths);
return [documentDir stringByAppendingPathComponent:#"abcd_DB.sqlite"];
}
**If you are using iOS Devices-
You can get Your DB directly by using https://macroplant.com/iexplorer Application.
**If you are using Simulator.
Get the Path directory
In terminal : open directory Path(Past your Directory Path).
Copy your DB and brows it with Firefox or sqlite browser.
It would seem that my apps no longer are able to save files to their documents folder when doing this:
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *dta = [[NSData alloc] init];
dta = [NSData dataWithContentsOfFile:path];
NSLog(#"writing file: %#", path);
if ([dta writeToFile:path options:NSAtomicWrite error:nil] == NO) {
NSLog(#"writeToFile error");
}else {
NSLog(#"Written: %#", path);
[self addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:path]];
}
I do get "Written" in the log with the full path:
Written: /var/mobile/Containers/Data/Application/ECBCD65D-A990-4758-A07F-ECE48E269278/Documents/9d440408-4758-4219-9c9c-12fe69cf82f2_pdf.pdf
And as long as I don't quit the app I can load the PDF in a UIWebView like this (pdfPath is a string that I pass to the function that loads the PDF file):
[www loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:pdfPath]]];
Any help at all is as always greatly appreciated.
Okay, after mucking about I found that since the documents directory changes path every time I run the app, I had to:
Write the file to the documents folder with the complete path to
the file:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent: fileName];
NSData *dta = [[NSData alloc] init];
dta = [NSData dataWithContentsOfFile:path];
if ([dta writeToFile:path options:NSAtomicWrite error:nil] == NO) {
NSLog(#"writeToFile error");
}else {
NSLog(#"Written: %#", path);
[self addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:path]];
}
Save only the file name to my database
Load the file by using the full newly generated Documents directory path and append the file name from my database:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent: pdfPath];
I have an App both in C# and Objective-C, that has to read from text file. Since the text file is created after the App, the user has the option to save it anywhere. In C# it was not difficult to find the file, only using file name with out the full path. In Objective-C this seems to be difficult. I can't ask the users to save it at specific Path, it is against Apple's App regulation. Any Idea how to search for the particular file with only filename? During my trial I used NSFileManager to detect the file, and the App can read the file if it is saved in Applications(Mac),But if i save the file in Documents or anywhere else , gives me Error:'file doesn't exist'.
You can save your txt file within your app folder. You can create directory.
Here is some code to create directory in Documents directory.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *flmngr = [NSFileManager defaultManager];
BOOL isDir;
if (![flmngr fileExistsAtPath:[NSString stringWithFormat:#"%#/yourDicretoryName", documentsDirectory] isDirectory:&isDir]) {
[flmngr createDirectoryAtPath:[NSString stringWithFormat:#"%#/yourDicretoryName", documentsDirectory]
withIntermediateDirectories:NO
attributes:nil
error:nil];
}
after creating specific directory. You can save your txt file. Assume you have one nsstring
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/txtFile.txt",documentsDirectory];
[yourString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
After saving your txt file you can read like this.
NSString *stringTxt = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
You can get the file list in directory using the code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError *error;
NSMutableArray *fileList = [[NSMutableArray alloc]initWithArray:[[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSString stringWithFormat:#"%#/yourDirectory", documentsDirectory] error:&error]];
-contentsOfDirectoryAtPath
returns NSArray Object. with the file names in directory.
For Cocoa Thouch Mac Application.
You can create directory using code:
NSFileManager *fileManager= [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:directory isDirectory:&isDir])
if(![fileManager createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:NULL])
NSLog(#"Error: Create folder failed %#", directory);
You can select directory using code:
NSOpenPanel* panel = [NSOpenPanel openPanel];
[panel setCanSelectHiddenExtension:NO];
[panel setCanChooseDirectories:YES];
[panel setCanChooseFiles:NO];
[panel setTitle:#"Kaydetmek için Dosya Yolunu Seçin!"];
[panel beginWithCompletionHandler:^(NSInteger result){
if (result == NSFileHandlingPanelOKButton) {
directoryPath = [[[panel URLs] objectAtIndex:0]path];
directoryPath = [directoryPath stringByReplacingOccurrencesOfString:#"file://localhost" withString:#""];
}
}];
Writing file still same. But you can save your in documents desktop in selected or created directory etc.
Fetching file list is same.
I've seen this question asked a few times but I have been unable thus far to achieve success using any of the post solutions. What I am trying to do is rename a file in the local storage of an app (also kind of new to Obj-c). I am able to retrieve the old path and create the new path, but what would I have to write in order to actually change the files name?
What I have thus far is:
- (void) setPDFName:(NSString*)name{
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString* initPath = [NSString stringWithFormat:#"%#/%#",[dirPaths objectAtIndex:0], #"newPDF.pdf"];
NSString *newPath = [[NSString stringWithFormat:#"%#/%#",
[initPath stringByDeletingLastPathComponent], name]
stringByAppendingPathExtension:[initPath pathExtension]];
}
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:initPath toPath:newPath error:&error];
The code is very messy; try this:
- (BOOL)renameFileFrom:(NSString*)oldName to:(NSString *)newName
{
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
NSString *oldPath = [documentDir stringByAppendingPathComponent:oldName];
NSString *newPath = [documentDir stringByAppendingPathComponent:newName];
NSFileManager *fileMan = [NSFileManager defaultManager];
NSError *error = nil;
if (![fileMan moveItemAtPath:oldPath toPath:newPath error:&error])
{
NSLog(#"Failed to move '%#' to '%#': %#", oldPath, newPath, [error localizedDescription]);
return NO;
}
return YES;
}
and call this using:
if (![self renameFileFrom:#"oldName.pdf" to:#"newName.pdf])
{
// Something went wrong
}
Better still, put the renameFileFrom:to: method into a utility class and make it a class method so it can be called from anywhere in your project.
I have a problem, I need to move the contents of a Documents subdirectory to the 'root' of Documents Directory.
To do this, I thought to copy all the contents of the subdirectory to Documents directory and then delete my subdirectory.
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentinbox = [documentsDirectory stringByAppendingPathComponent:#"inbox"]
This is how I get the path of Documents directory, and the path of my subdirectory named inbox.
NSArray *inboxContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentinbox error:nil];
NSFileManager *fileManager = [NSFileManager defaultManager];
Then I create an array with all documents in the subfolder, and initialize the file manager.
Now I have to implement the for cycle that for each document copy the document from the subdirectory to the Documents Directory.
for(int i=0;i<[inboxContents count];i++){
//here there is the problem, I don't know how to copy each file
I would like to use the method moveItemAtPath, but I don't know how to get the path of each file.
Hope you can understand my problem,
Thanks for help
Nicco
You can use moveItemAtPath:toPath:error: as follows.
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentinbox = [documentsDirectory stringByAppendingPathComponent:#"inbox"];
//Initialize fileManager first
NSFileManager *fileManager = [NSFileManager defaultManager];
//You should always check for errors
NSError *error;
NSArray *inboxContents = [fileManager contentsOfDirectoryAtPath:documentinbox error:&error];
//TODO: error handling if inboxContents is nil
for(NSString *source in inboxContents)
{
//Create the path for the destination by appending the file name
NSString *dest = [documentsDirectory stringByAppendingPathComponent:
[source lastPathComponent]];
if(![fileManager moveItemAtPath:source
toPath:dest
error:&error])
{
//TODO: Handle error
NSLog(#"Error: %#", error);
}
}