How could I have a complete list of each .plist path (inside iPhone/iPad) ?
In iOS Simulator I'm using it : ls -l ~/Library/Preferences/com.apple.*.plist
My goal is to find a specific key and read the boolean value in preferences.
Because I need to know if it is enable or not.
It is something that is missing in SDK but is existing in preferences.
NSLog (#"%#", [[NSBundle mainBundle] pathsForResourcesOfType:#"plist" inDirectory:#"/"]);
The method returns an NSArray.
You need to create the plist first. All you have to do is access it when you need it.
NSArray *thePlist;
NSString *plist = [[NSBundle mainBundle] pathForResource: #"plistFileName" ofType: #"plist"];
thePlist = [[NSArray alloc] initWithContentsOfFile: plist];
Thank you Daniel A. White , Jahm and Kedar!
I code this to summarize each comment :
With an extra, add an example to read UISupportedInterfaceOrientations values.
NSLog(#"Preferences plists from apple (inside iPhone/iPad) are not accessible from code");
NSLog (#"Accessible plist paths : %#", [[NSBundle mainBundle] pathsForResourcesOfType:#"plist" inDirectory:#"/"]);
NSArray *pList = [[NSBundle mainBundle] pathsForResourcesOfType:#"plist" inDirectory:#"/"];
for (int i = 0; i < [pList count]; i ++)
{
NSString *plistPath = [pList objectAtIndex:i];
NSDictionary *plistDictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];
NSMutableArray *nameString = [plistDictionary objectForKey:#"UISupportedInterfaceOrientations"];
for (NSString *n in nameString)
{
NSLog(#"Supported Interface : %#",n);
}
}
Related
I've already looked at Parse Plist (NSString) into NSDictionary and deemed it to be not a duplicate, as that question and its answer do not address my concerns.
I have a .plist file in the file system structured like this:
The source code of this .plist file looks like this:
{
"My App" = {
"Side Panel" = {
Items = {
Price = "#123ABC";
};
};
};
}
I know how to get an item in the Root like this:
[[NSBundle mainBundle] pathForResource:#"filename" ofType:#"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSString value = [dict objectForKey:#"key"]);
But what if the structure is like mine, with tiered dictionaries? How do I get the value of Price?
I would like to do this all in one method, ideally like this:
Calling
NSString *hexString = [self getColorForKey:#"My App.Side Panel.Items.Price"];
Definition
- (NSString *) getColorForKey: (NSString *)key
{
NSArray *path = [key componentsSeparatedByString:#"."];
NSDictionary *colors = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Colors" ofType:#"plist"]];
NSString *color = #"#FFFFFF"; // white is our backup
// What do I put here to get the color?
return color;
}
Here's the solution that worked for me:
+ (NSString*) getHexColorForKey:(NSString*)key
{
NSArray *path = [key componentsSeparatedByString:#"."];
NSDictionary *colors = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Colors" ofType:#"plist"]];
NSString *color = #"#FFFFFF";
for (NSString *location in path) {
NSObject *subdict = colors[location];
if ([subdict isKindOfClass:[NSString class]])
{
color = (NSString*)subdict;
break;
}
else if ([subdict isKindOfClass:[NSDictionary class]])
{
colors = (NSDictionary*)subdict; // if it's a dictinoary, our color may be inside it
}
else
{
[SilverLog level:SilverLogLevelError message:#"Unexpected type of dictinoary entry: %#", [subdict class]];
return color;
}
}
return color;
}
where key is an NSString that matches /^[^.]+(\.[^.]+)*$/, meaning it looks like my targeted #"My App.Side Panel.Items.Price".
Yes I understand what you're looking to accomplish; thank you for the clarification. I will however add that the resources and advice I have written do provide the necessary information resolve your problem.
That said, the following gets your dictionary:
NSURL *plistURL = [[NSBundle mainBundle] URLForResource:#"Info" withExtension:#"plist"];
NSData *plistData = [NSData dataWithContentsOfURL:plistURL];
NSDictionary *tieredPlistData = [NSPropertyListSerialization propertyListWithData:plistData
options:kCFPropertyListImmutable
format:NULL
error:nil];
Then, if we're interested in the information contained in Items
NSDictionary *allItemsDictionary = tieredPlistData[#"My App"][#"Side Panel"][#"Items"];
Assuming that Items will contain a number of objects, you could use
NSArray *keys = [allItems allKeys];
for(NSString *key in keys){
NSString *colorValue = allItemsDictionary[key];
// do something with said color value and key
}
Or, if there is a single value you need, then just reference that key
NSString *colorForPriceText = allItemsDictionary[#"Price"];
But a few tips:
It's generally considered a better idea to keep frequently accessed values in code instead of a plist/file that is loaded at runtime.
That said, you wouldn't put your call to load from NSBundle in the same method you would use to query a specific value. In your example, every time you need a color, you end up re-accessing NSBundle and pile on unneeded memory allocations. One method would load the plist into an iVar NSDictionary and then that NSDictionary would be used separately by another method.
I have created save.plist in a resource folder. I have written some data within that directly (without using coding). I am able to read that data but I'm not able to write through code to the same save.plist. By using following code I am trying to write the data but it gets stored within my .app plist.
The code is here
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSString *plistPath = [[NSBundle mainBundle] pathForResource:#"save" ofType:#"plist"];
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSMutableDictionary *temp = (NSMutableDictionary *)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format errorDescription:&errorDesc];
if (!temp) {
NSLog(errorDesc);
[errorDesc release];
}
// [temp setValue:#"123" forKey:#"line1"];
// [temp writeToFile:plistPath atomically: YES];
//Reading data from save.plist
NSLog([temp objectForKey:#"name"]);
NSLog([temp objectForKey:#"wish"]);
NSNumber *num=[temp valueForKey:#"roll"];
int i=[num intValue];
printf("%d",i);
//writitng the data in save.plist
[temp setValue:#"green" forKey:#"color"];
[temp writeToFile:plistPath atomically: NO];
NSMutableDictionary *temp1 = (NSMutableDictionary *)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format errorDescription:&errorDesc];
NSLog([temp objectForKey:#"color"]);
I want that, the data which I want to write should get written into save.plist only which is stored in references. I am new with this concept. So if anyone knows it please help me.
Thanks in advance.
:-)
I don't know if I understand your question, but if you want to write into a .plist within your .app bundle you are probably doing something wrong. If you want to store preferences, you should consider using NSUserDefaults.
If you really want to modify a bundled .plist - here is some code:
NSString *plistPath = nil;
NSFileManager *manager = [NSFileManager defaultManager];
if (plistPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:#"Contents/Info.plist"])
{
if ([manager isWritableFileAtPath:plistPath])
{
NSMutableDictionary *infoDict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
[infoDict setObject:[NSNumber numberWithBool:hidden] forKey:#"LSUIElement"];
[infoDict writeToFile:plistPath atomically:NO];
[manager changeFileAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate] atPath: [[NSBundle mainBundle] bundlePath]];
}
}
Update:
Nate Flink pointed out that some of the NSFileManager methods used above are deprecated.
He posted an answer with the replacement methods below:
https://stackoverflow.com/a/12428472/100848
Updated version of the original awesome example by weichsel (thank you!). Xcode threw a couple warnings one of which is a deprecated method on NSFileManager. Updated here with non-deprecated methods from iOS 5.1
NSString *plistPath = nil;
NSFileManager *manager = [NSFileManager defaultManager];
if ((plistPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:#"mySpecial/PathTo.plist"]))
{
if ([manager isWritableFileAtPath:plistPath])
{
NSMutableDictionary *infoDict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
[infoDict setObject:#"foo object" forKey:#"fookey"];
[infoDict writeToFile:plistPath atomically:NO];
[manager setAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate] ofItemAtPath:[[NSBundle mainBundle] bundlePath] error:nil];
}
}
When you build the app, it will create an executable file "appName.app" and all the files are built in the bundle. Therefore, you can't access to resource folder when the app is running because all the data is in the bundle(not in folder).
However, you can access to a temp folder which contains some information of the app.
You can find the temp folder here:
Open finder--click on your username(under PLACES)--Library--Application Support--iPhone Simulator--User--Applications--(here you can find all the temp folders of your iPhone apps)
You can access to this temp folder by:
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
If you name your file save.plist, you can access to it like this:
NSString *filePath = [documentsDirectory stringByAppendingString:#"_save.plist"];
Then you just save your file to this filePath and it will appear in the temp folder named "Documents_save.plist".
*Note that the temp folder's name varies every time you run the app.
Recommend a book for you: 《Beginning iPhone Development--Exploring the iPhone SDK》. In Chapter 11 you can find what you want.
To summarize some of the other answers:
You're problem is that you're trying to write the file back into the folder that contains your application. That folder is not writable at runtime. Everything you're doing is fine, you just need to pick a different location to write your file to.
You can use the NSSearchPathForDirectoriesInDomains function to find a more suitable folder for this data. (Such as the #"Documents" folder.)
try this:
-(void)add:(NSRunningApplication *) app {
if ([self contains:app]) return;
[self.apps addObject:app.localizedName];
[self.apps writeToFile:self.dataFile atomically:YES];
}
from "Cocoa Programming".
you have to copy your plist into document directory...
because you cannot save anything without saving into document file....when you copied it will allow to write/modify on plist
In my application I am not able to get the plist using the below code. I am using Xcode 4.5
and here is my code for retrieving plist,
NSBundle *thisBundle = [NSBundle mainBundle];
NSDictionary *theDictionary;
NSString *commonDictionaryPath;
if (commonDictionaryPath = [thisBundle pathForResource:#"newfonts-Info" ofType:#"plist"])
{
theDictionary = [[NSDictionary alloc] initWithContentsOfFile:commonDictionaryPath];
}
Note:- If I try to retrieve a text or xml file then the above code works fine.
To get the Info plist as a dictionary, you can just do:
NSDictionary *theDictionary = [[NSBundle mainBundle] infoDictionary];
Use
[[NSBundle mainBundle] infoDictionary];
Calling infoDictionary on any bundle instance will return something (thought it may only contain private keys).
Try this code
SArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString* fooPath = [[NSBundle mainBundle] pathForResource:#"newfonts-Info" ofType:#"plist"];
NSLog(fooPath);
contentArray = [NSArray arrayWithContentsOfFile:fooPath];
NSLog(#"%#",contentArray);
or this can also works with NSDictionary
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"newfonts-Info" ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
NSLog(#"%#",dict);
i hope it helps you.
Finally I find the answer by self
I just open the documents directory and open the application.app file and got to see that the plist file which is shown as application-Info.plist in the bundle is seen just as Info.plist
so I changed the above code and and retrieve the dictionary
NSString *commonDictionaryPath;
commonDictionaryPath=[[NSBundle mainBundle]pathForResource:#"Info" ofType:#"plist"];
NSDictionary *info=[NSDictionary dictionaryWithContentsOfFile:commonDictionaryPath];
NSLog(#"path %#",commonDictionaryPath);
I know the question might look similar to many previously-asked questions, but I haven't been able to understand what to do after reading all those questions and answers.
I want to write a number of words that have wordNames and wordDefinitions, and some ID and a date ID. I have the following code, but I have two questions about the dictionary using an array with different data types, and the way of defining keys for the dictionary.
Please correct me if the whole .plist file I'm making is wrong.
Thanks in advance.
- (IBAction)addWord:(id)sender
{
NSString *destinationPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
destinationPath = [destinationPath stringByAppendingPathComponent:#"Box.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:destinationPath])
{
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:#"Box" ofType:#"plist"];
[fileManager copyItemAtPath:sourcePath toPath:destinationPath error:nil];
}
// Load the Property List.
NSMutableArray* wordsInTheBox = [[NSMutableArray alloc] initWithContentsOfFile:destinationPath];
NSString *wordName = word.name;
NSString *wordDefinition = word.definition;
NSInteger deckID;
NSDate addedDate;
//is this correct to have an array of different types?
NSArray *values = [[NSArray alloc] initWithObjects:wordName, wordDefinition, deckID, addedDate, nil];
//How and where am I supposed to define these keys?
NSArray *keys = [[NSArray alloc] initWithObjects: NAME_KEY, DEFINITION_KEY, DECK_ID_KEY, DATE_KEY, nil];
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:values forKeys:keys];
[wordsInTheBox addObject:dict];
[wordsInTheBox writeToFile:destinationPath atomically:YES];
}
initWithContentsOfFile: always returns an immutable array. You should to this:
NSMutableArray *wordsInTheBox = [[NSMutableArray alloc] initWithArray:[NSArray arrayWithContentsOfFile:destinationPath]];
What I don't entirely understand is where the word variable is defined. Is it an ivar?
If you're using the latest version of Xcode (4.4 or 4.5) I recommend using the much simpler literals for creating a dictionary.
NSDictionary *dict = #{NAME_KEY : wordName,
DEFINITION_KEY : wordDefinition,
DECK_ID_KEY : deckID,
DATE_KEY : addedDate};
But I don't see a problem with your dictionary definition either. It should work.
You have to make sure NAME_KEY, DEFINITION_KEY etc. are defined somewhere. All caps are usually only used for preprocessor macros, so you could do something like this:
#define NAME_KEY #"Name"
#define DEFINITION_KEY #"Definition"
You could also simply use the strings directly in your dictionary:
NSDictionary *dict = #{#"Name" : wordName,
#"Definition" : wordDefinition,
#"DeckID" : deckID,
#"Date" : addedDate};
But using macros isn't a bad idea either.
I am implementing a application based on web services. In that I need to add a string as property in .plist and I need to get the value from the .plist whenever I need in the code.
Here is a code sample:
NSString *path = [[NSBundle mainBundle] pathForResource: #"YourPLIST" ofType: #"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile: path];
id obj = [dict objectForKey: #"YourKey"];
NSBundle* mainBundle = [NSBundle mainBundle];
// Reads the value of the custom key I added to the Info.plist
NSString *value = [mainBundle objectForInfoDictionaryKey:#"key"];
//Log the value
NSLog(#"Value = %#", value);
// Get the value for the "Bundle version" from the Info.plist
[mainBundle objectForInfoDictionaryKey:#"CFBundleVersion"];
// Get the bundle identifier
[mainBundle bundleIdentifier];
NSURL *url = [[NSBundle mainBundle] URLForResource:#"YOURPLIST" withExtension:#"plist"];
NSArray *playDictionariesArray = [[NSArray alloc ] initWithContentsOfURL:url];
NSLog(#"Here is the Dict %#",playDictionariesArray);
or you can use following also
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Sample.plist"];
Get from plist is very simple.
NSString *path = [[NSBundle mainBundle] pathForResource:#"SaveTags" ofType:#"plist"];
if (path) {
NSDictionary *root = [NSDictionary dictionaryWithContentsOfFile:path];
}
If you want to add something to a plist, maybe you can find the answer here:
How to write data in plist?
But if you only want save some message in you app, NSUserDefaults is the better way.
You can not do this. Any Bundle wether it is iOS or Mac OS is readonly, you can only read to it and you can't create files, write or do anything with the files in a bundle. This is part of the Security features of apple. You can use the NSDocumentsDirectory to writr and read your stuff you need for your app
Swift
I know this was asked 12+ years ago. But this was the first SO question to come up via google. So to save time for everyone, here is how to do this in swift:
struct Config {
// option 1
static var apiRootURL: String {
guard let value = (Bundle.main.object(forInfoDictionaryKey: "BASE_URL") as? String), !value.isEmpty else {
fatalError("Base URL not found in PLIST")
}
return value
}
// option 2
static var databaseName: String {
guard let value = (Bundle.main.infoDictionary?["DB_NAME"] as? String), !value.isEmpty else {
fatalError("DB NAME not found in PLIST")
}
return value
}
}
Notice the 2 functions use slightly diffrent methods to access the plist. But in effect they are almost the same.
In theory there might not be a plist. Hence infoDictionary is optional. But in this case the first method will also return an unexpected value, resulting in an error.
One actual difference as noted by Apple:
Refering to Bundle.main.object(forInfoDictionaryKey: "BASE_URL")
Use of this method is preferred over other access methods because it returns the localized value of a key when one is available.