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.
Related
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];
i want to copy all type of file that place in document directory to a another directory in ios,
if ([fileManager fileExistsAtPath:txtPath] == YES) {
[fileManager removeItemAtPath:txtPath error:&error];
}
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:#"txtFile" ofType:#"txt"];
[fileManager copyItemAtPath:resourcePath toPath:txtPath error:&error];
I M Using This Code But it is only help in specific one type of file.
Finally I got My Answer After Doing Some Changes and finding from the other reference and i found this code that running perfect for me
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePathsArray1 = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:dataPath error:nil];
Check the below code to get all type of files from a directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *filePaths = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
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];
I need to search a file in documents directory of iOS but i don't know the extension of that file. How to search the file without extension.
Below is the code if you know the filename.extension(abc.txt). How can i search for the same file with jsut filename(abc)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"abc.txt"];
NSString *content = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding error:NULL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSString *fileWithExt = nil;
for (NSString *file in directoryContent )
{
if([file stringByDeletingPathExtension] isEqualsTo:#"abc"]
{
fileWithExt = file;
break;
}
}
P.S. : The fileWithExt will contain the first file with name abc
I m able to save the plist file in Simulator but I m not able to save the Plist file in the device. Any suggestion.
I m using
NSString* dictPath = [[NSBundle mainBundle] pathForResource:#"Dictionary" ofType:#"plist"];
NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfFile:dictPath];
to read the files
and
[dict writeToFile:dictPath atomically: YES];
to write to file.
You can not write in to main bundle. You only can read from main bundle. If you want to write an file you need to place it in to the documents directory of your app.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",plistName]];
If you need the plist from the main bundle you can copy it first in to the documents directory then modify it. It is advised to have a check to ensure it is copied only once.
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",plistName]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]){
NSLog(#"File don't exists at path %#", path);
NSString *plistPathBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:#"plist"];
[fileManager copyItemAtPath:plistPathBundle toPath: path error:&error];
}else{
NSLog(#"File exists at path:%#", path);
}
Generally you would store these in ~/Documents or in ~/Library depending on the file. The question What is the documents directory (NSDocumentDirectory)? includes the documentation links and sample code you need to understand this.
You need to save the plist in Documents directory
to write
NSString *mainBundlePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dictPath = [mainBundlePath stringByAppendingPathComponent:#"Dictionary"];
NSDictionary * dict = ...; //Construct your dictionary
[dict writeToFile:dictPath atomically: YES];
to read
NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfFile:dictPath];