How to store a NSData locally - ios

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];

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.

pathForResource doesn't return an array

I have 2 methods, one for saving an array to a file and one for loading an array from the file, but when I'm trying to read an array, nothing happens, like an array is empty.
My code:
- (IBAction)write:(id)sender
{
NSArray *array = [racersArray copy];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libraryDirectory = [paths objectAtIndex:0];
NSString *location = [libraryDirectory stringByAppendingString:#"/history.plist"];
[array writeToFile:location atomically:YES];
}
- (IBAction)read:(id)sender
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"file" ofType:#"plist"];
NSArray *array = (path != nil ? [NSArray arrayWithContentsOfFile:#"/history.plist"] : nil);
}
You are reading/writing from/to two different places.
You write to the Library folder (it should be under Library/Application Support or some such, but I digress).
You read from the app bundle.
Try with this Methods may be helps you.👍
For Save
-(IBAction)save_Action:(id)sender{
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"manuallyData.plist"];
[plistData writeToFile:plistPath atomically:YES];
}
For Get Path
-(IBAction)retrive:(id)sender{
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"manuallyData.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
plistPath = [[NSBundle mainBundle] pathForResource:#"manuallyData" ofType:#"plist"];
}
}
- (IBAction)savetapped:(id)sender {
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"json.geojson"];
[paths writeToFile:plistPath atomically:YES];
}
- (IBAction)retriveTapped:(id)sender {
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"json.geojson"];
NSLog(#"%#",documentsPath);
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
plistPath = [[NSBundle mainBundle] pathForResource:#"json" ofType:#"geojson"];
}
NSLog(#"%#",plistPath );
}
Took a while to figure out that I don't actually know what you are trying to do.
pathForResource gives you paths for resource in your application bundle. You can only read from there. You can never write there. Sometimes people have the initial version of a file in the application bundle and then write it somewhere else. If that's what you want then most likely you need to:
(1) write a method that returns the path where the array will be stored once your application has been running.
(2) The "write" method calls this path method to know where to write the array.
(3) The "read" method calls this path method to know where to read the array, then you read it. However, the array can be nil because your app was run the first time, or the array wasn't written correctly. In that case, you use pathForResource to get the path where the file would be in your application bundle, and read it from there.

How to delete files cached in supporting files?

I use the following code to store an NSMutableArray into a file:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePathHit = [documentsDirectory stringByAppendingPathComponent:#"hit"];
[NSKeyedArchiver archiveRootObject:self.arrayHit toFile:filePathHit];
and the code below to retrieve data from the file:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePathHit = [documentsDirectory stringByAppendingPathComponent:#"hit"];
NSMutableArray *unarchivedHit = [NSKeyedUnarchiver unarchiveObjectWithFile:filePathHit];
It works fine but the file been written to seems reside there all the time, so each time I relaunch my application, it reads data from there. But what I want to achieve is the data only resides there during the application operates, and once the app's shut down the data been cleared. How can I achieve this? Thanks.
You can use NSFileManager:
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:filePathHit error:&error];

Try to write a string to file [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Problem in writing to a file in application bundle
I am trying to write a String to a file using the following code :
NSString *file = [[NSBundle mainBundle] pathForResource:#"settings" ofType:#"txt"];
NSLog(#"Path : , %#", file);
NSError *error=NULL;
NSString *data=#"teleiwne";
[data writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:&error];
The print out of Path is : /Users/kd/Library/Application Support/iPhone Simulator/6.0/Applications/763B8245-CB1A-4BDE-85CF-19AEFA411DB8/testKremala.app/settings.txt
I don't get any error but nothing is written to file
I tried the following code and it worked :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"set.txt"];
NSString *data=#"Kostas";
[data writeToFile:appFile atomically:YES];
NSString *myData = [NSString stringWithContentsOfFile:appFile];
NSLog(#"Data : %# ",myData);
You aren't allowed to write to the App directory. Try writing to the Documents directory inside that app folder.
NSString *data = #"testData";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"settings.txt"];
[data writeToFile:appFile atomically:YES];

Using Documents Directory for HTML Img

I'm trying to use the app's Documents directory to store images, and later access then with a webview with html. I tried using the /var/mobile/Applications/id/Documents but that didn't work. Is there a way to access those files in the webview?
For save image you have to download image like a NSMutableData in your Cache directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDirectory = [paths objectAtIndex:0];
NSString* filePath = [NSString stringWithFormat:#"%#/imageTemp.png",cachesDirectory];
[imageData writeToFile:filePath atomically:YES];
After donwload you can move your image to your Document directory:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *arrayPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [arrayPath objectAtIndex:0];
NSString *cacheImagePath = filePath;
NSError *error;
[fileManager copyItemAtPath:cacheImagePath toPath:documentPath error:&error];
Turned out I missed a / so it should of been file:///var/mobile/Applications/id/Documents then it worked.

Resources