I am trying to get a dictionary from a plist in ios.The problem is the code is not working.It works in a different function but not this one.
NSDictionary* pdata=[NSDictionary dictionaryWithContentsOfFile:datapath];
The file exists at path but for some reason its not working.I get null when I try to print the dictionary.
EDIT: Here is my path/private/var/mobile/Applications/F4D5EFE8-58FC-4179-9492-4C4F9FD01024/Library/Preferences/abc.def.ghi.plist.This is a jailbroken application and I was able to do this successfully for another pplist in a seperate location.
This Should Work Fine.
NSString *plistFileUrl=[[NSBundle mainBundle] pathForResource:#"someplistFile" ofType:#"plist"];
NSURL *url=[NSURL fileURLWithPath:plistFileUrl];
NSDictionary *aDict=[[NSDictionary alloc] initWithContentsOfURL:url];
This must work for you.
NSString *aStr=[[NSBundle mainBundle] pathForResource:#"Property List" ofType:#"plist"];
NSURL *aUrl=[NSURL fileURLWithPath:aStr];
NSDictionary *aDict=[[NSDictionary alloc] initWithContentsOfURL:aUrl];
Try this .
NSDictionary* dict = [NSDictionary dictionaryWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"example" ofType:#"plist"]isDirectory:NO]];
NSLog(#"data is %#",dict);
Try this
//Local mainbundle
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *filePath = [path stringByAppendingPathComponent:#"Contents.plist"];
NSMutableDictionary *dictContent = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
NSLog(#"%#",dictContent);
///DocumentsDirectory
NSMutableDictionary *dictItem=[[NSMutableDictionary alloc]init];
[dictItem setObject:#"ravi" forKey:#"name"];
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *docFilePath = [documentsDirectoryPath
stringByAppendingPathComponent:#"data.plist"];
[dictItem writeToFile:docFilePath atomically: YES];
NSMutableDictionary *dictContent1 = [NSMutableDictionary dictionaryWithContentsOfFile:docFilePath];
NSLog(#"%#",dictContent1);
Related
I'm modifying someone elses code and struggling to access values within a plist, I can access Info.plist etc.. with code such as:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"Info.plist"];
NSDictionary *plistData = [NSDictionary dictionaryWithContentsOfFile:finalPath];
NSLog(#"ret=%#", plistData);
However when trying to access Account.plist, it returns null, I'm assuming it's a path issue?
Any help/pointers appreciated.
Here are examples of how to get either a Dictionary or an Array out of a plist.
//*******************************************
- (NSArray *)loadArrayFromPlist:(NSString *)plistName {
NSString *plistPath = [[NSBundle mainBundle] pathForResource: plistName ofType: #"plist"];
return [NSArray arrayWithContentsOfFile: plistPath];
}
//*******************************************
- (NSDictionary *)loadDictionaryFromPlist:(NSString *)plistName {
NSString *plistPath = [[NSBundle mainBundle] pathForResource: plistName ofType: #"plist"];
return [NSDictionary dictionaryWithContentsOfFile: plistPath];
}
Hello I have the following code which works perfect, it finds the Plist and assigns the NSDictionary to my NSArray called landingSites. The only problem is I want the user to be able to add sites so need to store the Plist in the user documents instead of the NSBundle:
plistPath = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
NSMutableDictionary *newDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
dictionaryKeys = [newDictionary allKeys];
self.landingSites = [dictionaryKeys sortedArrayUsingSelector:#selector(compare:)];
self.dictionaryFromPlist = newDictionary;
[Picker selectRow:0 inComponent:0 animated:NO];
for(NSString *parent in dictionaryKeys)
{
NSDictionary *parentData = [dictionaryFromPlist objectForKey:parent];
NSArray *child = [parentData objectForKey:#"Name"];
NSLog(#"%#", child);
}
So far I have produced the code below, but whenever I run the program, the if-statement ALWAYS executes as if the plist in never copied to the user documents. Also I do not know how to attach the NSDictionary contents to my landingSites array as I did above. Please help
(void) viewDidLoad {
[super viewDidLoad];
NSError *error;
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Data.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:path]) {
NSLog(#"copying database to users documents");
NSString *pathToSettingsBundle = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
[fileManager copyItemAtPath:pathToSettingsBundle toPath:path error:&error];
}
else{
NSLog(#"users database already configured");
}
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask,YES);
NSDocumentationDirectory is wrong. You are looking for NSDocumentDirectory or NSLibraryDirectory.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
I am using writeToFile:atomically: to update the value of a key in my plist by 1 every time the app is launched. I put this code in viewDidLoad, which reads the string value of the key, gets the numeric value of that string, increases it by 1, converts it back to a string, and writes that as the new string for that key, but when I read it again it seems to have not updated. I can't figure out what I'm doing wrong. I don't need a special framework for writeToFile:atomically:, do I?
Here is the code:
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"DaysLaunched.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"DaysLaunched" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath:path error:&error];
}
NSMutableDictionary *plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
NSString *currentNumberOfDays = [NSString stringWithFormat:#"%#",[plistDict objectForKey:#"numberOfDays"]];
NSLog(#"currentNumberOfDays = %#", currentNumberOfDays); //0
int days = [currentNumberOfDays intValue];
days ++;
currentNumberOfDays = [NSString stringWithFormat:#"%d", days];
[data1 setObject:[NSString stringWithFormat:#"numberOfDays"] forKey:currentNumberOfDays];
NSLog(#"currentNumberOfDays = %#", currentNumberOfDays); //1
[data1 writeToFile: path atomically:YES];
currentNumberOfDays = [NSString stringWithFormat:#"%#",[plistDict objectForKey:#"numberOfDays"]];
NSLog(#"currentNumberOfDays = %#", currentNumberOfDays); //0 ??????? writeToFile isn't working?
And here is a screenshot of "DaysLaunched.plist" in my 'Supporting Files' folder, (I've also verified that the plist file name is spelled exactly the same way I spelled it in my code, via Copy-Paste)
The original plist file is also in my 'Copy Bundle Resources' in targets.
Try
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"DaysLaunched.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"DaysLaunched"
ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath:path error:&error];
}
NSMutableDictionary *plistDict = [NSMutableDictionary dictionaryWithContentsOfFile:path];
NSInteger days = [plistDict[#"numberOfDays"] integerValue];
plistDict[#"numberOfDays"] = [#(++days) stringValue];
[plistDict writeToFile: path atomically:YES];
You have made a mistake while setting your data.
You should do:
[data1 setObject:currentNumberOfDays forKey:#"numberOfDays"];
instead of:
[data1 setObject:[NSString stringWithFormat:#"numberOfDays"] forKey:currentNumberOfDays];
i have a plist named as "config.plist" in xcode ,i tried to retrieve register url (key :reg ) but when i print that result it showing null value?
This is my code to retrieve string ..please refer image for my plist structure.
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: [[_config objectForKey:#"URL"] objectForKey:#"reg"]]];
NSString *plist=[[NSBundle mainBundle] pathForResource:#"config" ofType:#"plist"];
NSDictionary *dict=[[NSDictionary alloc] initWithContentsOfFile:plist];
NSString *stringValue=dict[#"URL"][#"reg"];
EDIT: Very Important to understand the following:
In the above dict itself is the objectForKey:#"Root"
And I/we trying to find by [#"Root"][#"URL"][#"reg"] which is not there.
So for readability with namingConventions(what it stores) it should be :
NSString *plist=[[NSBundle mainBundle] pathForResource:#"config" ofType:#"plist"];
NSDictionary *rootDict=[[NSDictionary alloc] initWithContentsOfFile:plist];
NSString *stringValue=dict[#"URL"][#"reg"];
Or, even
NSString *plist=[[NSBundle mainBundle] pathForResource:#"config" ofType:#"plist"];
NSString *stringValue=[[NSDictionary alloc] initWithContentsOfFile:plist][#"URL"][#"reg"];
Try
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"config.plist"];
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:path];
NSString *result = [[[dictionary objectForKey:#"Root"] objectForKey:#"URL"]objectForKey:#"reg"];
Edit for Resource:
NSString *path = [[NSBundle mainBundle] pathForResource:#"config" ofType:#"plist"];
Try This Code
NSString *plistFilePath=[[NSBundle mainBundle] pathForResource:#"config" ofType:#"plist"];
NSDictionary *urlDictionary=[[NSDictionary alloc] initWithContentsOfFile:plistFilePath];
NSString *urlString=[[urlDictionary objectForKey:#"URL"] valueForKey:#"reg"];
NSString *plist=[[NSBundle mainBundle] pathForResource:#"config" ofType:#"plist"];
NSLog(#"path%#",plist);
NSDictionary *dict=[[NSDictionary alloc] initWithContentsOfFile:plist];
NSLog(#"d%#",dict);
NSString *stringValue=[[dict objectForKey:#"URL"] valueForKey:#"reg"];
This thing works for me..Thanks for your all help
I have followed this answer to write data to the plist
How to write data to the plist?
But so far my plist didn't change at all.
Here is my code :-
- (IBAction)save:(id)sender
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"drinks" ofType:#"plist"];
NSString *drinkName = self.name.text;
NSString *drinkIngredients = self.ingredients.text;
NSString *drinkDirection = self.directions.text;
NSArray *values = [[NSArray alloc] initWithObjects:drinkDirection, drinkIngredients, drinkName, nil];
NSArray *keys = [[NSArray alloc] initWithObjects:DIRECTIONS_KEY, INGREDIENTS_KEY, NAME_KEY, nil];
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:values forKeys:keys];
[self.drinkArray addObject:dict];
NSLog(#"%#", self.drinkArray);
[self.drinkArray writeToFile:path atomically:YES];
}
Do I need to perform something extra?
I am new to iPhone SDK so any help would be appreciated.
You are trying to write the file to your application bundle, which is not possible. Save the file to the Documents folder instead.
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
path = [path stringByAppendingPathComponent:#"drinks.plist"];
The pathForResource method can only be used for reading the resources that you added to your project in Xcode.
Here's what you typically do when you want to modify a plist in your app:
1. Copy the drinks.plist from your application bundle to the app's Documents folder on first launch (using NSFileManager).
2. Only use the file in the Documents folder when reading/writing.
UPDATE
This is how you would initialize the drinkArray property:
NSString *destPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
destPath = [destPath stringByAppendingPathComponent:#"drinks.plist"];
// If the file doesn't exist in the Documents Folder, copy it.
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:destPath]) {
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:#"drinks" ofType:#"plist"];
[fileManager copyItemAtPath:sourcePath toPath:destPath error:nil];
}
// Load the Property List.
drinkArray = [[NSArray alloc] initWithContentsOfFile:destPath];