Accessing NSDocumentDirectory on iPad Simulator - objective-c

I've added a very simple .csv file to my app's NSDocumentDirectory using:
-(IBAction)exportModule:(id)sender{
NSString *fileName = #"exportedfile.csv";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *exportString = #"I've,been,exported";
NSData *testData=[exportString dataUsingEncoding:NSUTF8StringEncoding];
NSString *docDir = documentsDirectory;
NSString *completePath = [docDir stringByAppendingPathComponent:fileName];
[testData writeToFile:completePath atomically:YES];
if ([[NSFileManager defaultManager] fileExistsAtPath:completePath]) {
NSLog(#"Theres a file here!");
}
}
The app gets into the if statement printing "Theres a file here!", however I would like open the file and see if there were any problems in formatting the .csv.
If I were running on a physical device, I'd be able to open it up in iTunes and take a look there, but is there a way to examine the .csv while only using the simulator?

I have this at the beginning of all of my programs for using the simulator
NSLog(#"Documents: %#", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]);

Related

How to get file from destination path

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.

Using both NSApplicationSupportDirectory and NSDocumentDirectory

Here is the deal... I am creating an app (from another one of my apps) but I am altering to from using only the NSDocumentDirectory, which obviously allows the user to see all of the user files, to seeing only a few of the files... namely user created PDFs.
I have it working... but, nothing shows in the FileSharing/Documents window in iTunes.
First are the methods that invoke the NSApplicationSupportDirectory in the persistence model...
+(NSString *)getDocumentpath
{
//NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
return [paths objectAtIndex:0];
}
+(NSString *) documentsDirectoryPath
{
//NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}
+(void) copyResourceFileToDocumentsDirectory: (NSString *) fileName
{
//NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSFileManager * fileManager = [NSFileManager defaultManager];
BOOL succeeded = [fileManager fileExistsAtPath:writablePath];
NSError *error;
//If file is not in the documents directory then only write
if (!succeeded)
{
NSString *newPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
succeeded = [fileManager copyItemAtPath:newPath toPath:writablePath error:&error];
if (succeeded == FALSE) {
NSLog(#"%# : copy failed", fileName);
} else {
NSLog(#"%# : copy success", fileName);
}
} else {
NSLog(#"%# : already exists", fileName);
}
}
This is the method for saving the PDF into the NSDocumentDirectory, which has not been changed from the other app...
- (NSString*)saveJournalToPDF:(UIView*)journal andName:(NSString*)name
{
NSString* fileName = [NSString stringWithFormat:#"%#.pdf",name];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:fileName];
... // the rest of the data strings for creating the PDF
}
My question: how do I get ONLY the PDFs to be visible to the user without exposing the other data files? Right now, it seems that it is either all or nothing!
I neglected one small detail... setting the app to actually share files! The app's info.plist did not have "Application supports iTunes file sharing" set to YES. (UIFileSharingEnabled). Such a simple fix!!!

After Update, App Doesn't Load Existing Files from Documents Folder

I'm having an issue with loading existing images from the App's Documents Folder after ad-hoc update.
I've searched the internet for answers and I've found that I must use relative paths to files in order for the path to remain the same when the App is updated.
Can someone please show me how to do it ?
Right now I use the following to save the files (images) when ImagePicker finishes:
NSString *imageFilename = [NSString stringWithFormat:#"%#-profilePhoto.jpg",[NSDate date]];
NSArray *paths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
imagePath = [NSString stringWithFormat:#"%#/%#", paths, imageFilename];
Please help me out !
I've found the solution:
Instead of loading the images from the full path, I chose to make the system search for them after their name.
So instead of:
//Full path stored in a dictionary:
profilePhotoPath = [userDict objectForKey:#"profilepic"];
//Load the image from path:
profilePhoto = [[UIImage alloc] initWithContentsOfFile:profilePhotoPath];
I now use the following:
//Load image from documentsDirectory, filename
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
profilePhotoPath = [userDict objectForKey:#"profilepic"];
profilePhotoPath = [documentsDirectory stringByAppendingPathComponent:[profilePhotoPath lastPathComponent]];
profilePhoto = [[UIImage alloc] initWithContentsOfFile:profilePhotoPath];
By using "lastPathComponent" attribute I'm basically stripping out everything from the path except the filename and then I use NSSearch to give me my file.
This line makes the problem
NSArray *paths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
Here the issue is the variable paths is of type NSArray not NSString
Change it to,
NSString *paths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
or
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *paths = [path objectAtIndex:0];

Filtering file using it's type in iOS and put it in an array for specific directory

I need to look for files with a specific type and put them in an array. I've found code like this:
NSArray* pdfs = [[NSBundle mainBundle]
pathsForResourcesOfType:#"pdf" inDirectory:nil];
But this code accesses my application bundle, not the Documents directory.
I also found this code for getting the Documents directory:
NSString* doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);;
However, I just don't get how to get the path for a pdf file inside the Documents folder. I already tried to change the values of the parameters for inDirectory: in pdfs to be #"~/Documents" and still it can't change the directory path.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:#"abcd.pdf"];
BOOL success = [[NSFileManager defaultManager] fileExistsAtPath:documentsDirectory];
if (success == YES){
//Do your stuff here if file found at documents directory
}
else{
//file not found
}
To get the array of files at document directory :
NSError **error1;
NSArray *paths2 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDirectory2 = [paths2 objectAtIndex:0];
NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory2 error:error1];

iPad app - generating text file

Can someone explain and give example code to do the following steps in my iPad app:
do some things in my app, which generates some data (as a string)
write that data to a text file
be able to plug in my iPad to my computer and grab those text files off
How can I do this?
For writing string in a file use this
NSString *str = #"your string";
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:#"data.txt"];
NSError *error;
[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
Then set Application supports iTunes file sharing key to YES in your plist file.
When you connect your device with iTunes from there you can save your data.txt
Here is the video how to get files from iTunes
Edited as requested.
NSUserDefaults *deflt = [NSUserDefaults standardUserDefaults];
//this number file is saved, I'm not saving the file name as data0.txt.
//The first file to be saved is data1.txt
int num = [deflt integerForKey:#"fileNameNum"];
num++;
NSString *fileName = [NSString stringWithFormat:#"data%d.txt",num];;
NSString *str = #"your string";
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSError *error = nil;
[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (error == nil) {
//Save the number of the file that you have save in doc directory
[deflt setInteger:num forKey:#"fileNameNum"];
}