How to delete files cached in supporting files? - ios

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

Related

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

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 copy text file from document directory in iOS

Hello i am trying to copy text file from document directory into folder name Temp that located in document directory.
Here is some of code i tried and didn't work.
self.fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentsDirectoryToTemp = [NSString stringWithFormat:#"%#/Temp/",[paths objectAtIndex:0]];
NSString *txtPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.txt",tblGetNameToMove.textLabel.text]];
[self.fileManager copyItemAtPath:txtPath toPath:documentsDirectoryToTemp error:&error];
How can i do that?
There could be many reasons for this :
First try to print all the path like documentsDirectoryToTempn and txtPath whether it is correct or not .
The second thing is make use that error variable :
if(error)
{
NSLog("Error while coping :%#",[error localizedDiscription]);
}
so you can track exact problem .
Here is solution. I need to add directory and also name of file and extension.
Here is codes.
self.fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *txtPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.txt",tblGetNameToMove.textLabel.text]];
NSString *fileName = [NSString stringWithFormat:#"%#/Temp/%#.txt",documentsDirectory,tblGetNameToMove.textLabel.text];
[self.fileManager copyItemAtPath:txtPath toPath:fileName error:&error];

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.

Writing data into file

I'm trying to make a txt log file with the actions that happens in my app. I want to save some text whenever the app is connecting to the server o displaying new info.
Well, how do I write to a file? I've tried using the method writeToFile: but it's not working because fileExistsAtPath: is returning NO.
My code is:
NSString *file_path = #"mylog.txt";
NSString *log = #"Hello World!!\n";
[log writeToFile:file_path atomically:YES encoding:NSUnicodeStringEncoding error:nil];
Thanks!
PS: Oh, would it be readable through Organizer with the iPhone plugged in?
You should use the < App_Home >/Documents folder for storing Documents
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file_Path = [documentsDirectory stringByAppendingPathComponent:#"log.txt"];
[log writeToFile:file_path atomically:YES encoding:NSUnicodeStringEncoding error:nil];
But normally if you want to see and dump things while running the app,
you could just use NSLog() which outputs it in the console.
Try this method I wrote:
+(NSString*)createPath:(NSString*)fileName{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localizedPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",fileName]];
//NSLog(#"%#",localizedPath);
return localizedPath;
}
It will return you a path for your file. You only need to give it a name.

Resources