Read a .txt file inside documents directory - ios

How can I read a .txt file inside documents directory? Can you show me code?

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"txtFile.txt"];
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];

You can also use NSFileHandle for writing data in file and save to document directory:
You can follow: NSFileHandle

Related

How to open locally saved PDF file in an Objective C

I'm trying to save PDF file to local storage.
I save the file this way and it seems to me that everything is fine.
//Get path directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//Create PDF_Documents directory
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:#"PDF_Documents"];
[[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory withIntermediateDirectories:YES attributes:nil error:nil];
filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, tastingName];
[tastingNotesData writeToFile:filePath atomically:YES];
This way I try to get the file
tastingPath = /var/mobile/Containers/Data/Application/4255D8B0-33F5-47AA-ABFA-CCC3691DA033/Documents/PDF_Documents/39e0afcdb56240c2a65ab9e136377b32.pdf;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[self.productModel.tastingPath lastPathComponent]];
NSData *data2 = [[NSFileManager defaultManager] contentsAtPath:path];
NSLog(#"tasting notes %#", data2);
At the end file will be displayed in the UIWebView.
What am I doing wrong?
The problem is simple. In your attempt to read the PDF file, you don't include the PDF_Documents part of the path. Or you are not appending the filename. Can't be 100% sure which part is wrong. It depends on what the value of [self.productModel.tastingPath lastPathComponent] is.

How to store a NSData locally

I am getting various format of documents with extension as .png,.txt,.jpg,,mp3 etc as NSData formatt, I need to store these locally and view it ,I have tried this
NSData* conData = [convStr dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"the converted string to nsdata is :%#",conData);
[conData writeToFile:#"Filename.txt" atomically:YES];
but unfortunately this is not working can any one help.
Note - writing NSData into a file is an IO operation which may block your main thread use dispatch, also provide file path for writing instead file name only.
This writes file for me
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// Generate the file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Filename.txt"];
// Save it into file system
[data writeToFile:dataPath atomically:YES];
});
you should pass a correct path in writeToFile method
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *targetPatch = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:#"Filename.text"]];
[data writeToFile:targetPatch atomically:YES];
You have given only file name(Filename.txt) not whole file path thats why your code is not working.
Check below line of code you will get idea.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"Filename.txt"];
[urlData writeToFile:filePath atomically:YES];

Unzip Files in iOS

I have a .zip folder which contains some images. I want it to unzip into Documents directory in iOS device. I tried with the following link,
download and unzip file in iOS-Stack Overflow
Here is the code that I tried in my app,
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filepath = [documentsDirectory stringByAppendingPathComponent:#"Obj.zip"];
ZipArchive *zipArchive = [[ZipArchive alloc] init];
[zipArchive UnzipOpenFile:filepath Password:#""];
[zipArchive UnzipFileTo:[documentsDirectory stringByAppendingPathComponent:#"Obj"] overWrite:YES];
[zipArchive UnzipCloseFile];
And then I printed the all files in Document Directory, but the Obj.zip is the only file(Obj.zip is the file that wants to unzip) that exist in the Documents Directory. How can I done this?
Thanks in Advance!
Use SSZipArchive. Here is a sample code. https://github.com/soffes/ssziparchive
Also I believe the unzipping would create a folder in documents directory which would contain the files. Please check that
NSString *zipPath = [[NSBundle mainBundle] pathForResource:zipFileName ofType:#"zip"];
NSString *destinationPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath];
Update : Get zip file from documents directory
NSString *filename = #"MyZipFile.zip";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString * zipPath = [documentsDirectory stringByAppendingPathComponent:filename];
NSString *destinationPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath];

Why can't I save files to my iOS apps /Documents directory?

I am writing an app that can access the iOS root system, the user should be able to save files to his document directory. I am using this code to save the file to the document directory.
For Text:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self.filePath writeToFile:[NSString stringWithFormat:#"%#/%#", documentsDirectory, [self.filePath lastPathComponent]]
atomically:YES
encoding:NSUTF8StringEncoding error:nil];
For other files:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self.filePath writeToFile:[NSString stringWithFormat:#"%#/%#", documentsDirectory,[self.filePath lastPathComponent]]
atomically:YES];
My problem is I can save .txt files, but not other files, If I save for example .plist files with the save text methods, the contact is replaced by the directory path of the file. When I save a picture, or any other file it isn't readable. Is there a good method to save files without destroying them?
You're calling [self.filePath writeToFile:], thus writing the contents of the filePath variable to a file.
You should do something like:
[contents writeToFile:...]
Here you have an example of saving the image:
assuming you get the content of the image into NSData object:
NSData *pngData = UIImagePNGRepresentation(image);
then write it to a file:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
Have a look into these questions for more detailed explanations:
Write a file on iOS
Save An Image To Application Documents Folder From UIView On IOS

ipad - write NSString to text file

I have text file text.txt in my xcode project and I need to write NSString init from my iOS app. I've tried this code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex: 0];
NSString *docFile = [docDir stringByAppendingPathComponent: #"text.txt"];
NSString *content = #"Test";
[content writeToFile: docFile atomically: NO];
But it doesn't work for me... So can you help me with it?
this worked for me
//Method writes a string to a text file
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/text.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = #"Test";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}

Resources