Reading a plist - macos

I'm trying to read ~/Library/Preferences/com.apple.mail.plist (on Snow Leopard) to get the email address and other information to enter into the about dialog. I'm using the following code, which is obviously wrong:
NSBundle* bundle;
bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:#"~/Library/Preferences/com.apple.mail.plist" ofType:#"plist"];
NSDictionary *plistData = [NSDictionary dictionaryWithContentsOfFile:plistPath];
NSString *item = [plistData valueForKeyPath:#"MailAccounts.Item 2.AccountName"];
NSLog(#"Result = %#", item);
Moreover, the value I need to read is MailAcounts -> Item 2 -> AccountName and I am not sure I am doing this correctly (due to the space in the Item 2 key).
I tried reading Apple's developer guide to plist files but no help there.
How can I read a plist and extract the values as an NSString?
Thanks.

The first level is an array, so you need to use "MailAccounts.AccountName" and treat it as NSArray*:
NSString *plistPath = [#"~/Library/Preferences/com.apple.mail.plist" stringByExpandingTildeInPath];
NSDictionary *plistData = [NSDictionary dictionaryWithContentsOfFile:plistPath];
NSArray *item = [plistData valueForKeyPath:#"MailAccounts.AccountName"];
NSLog(#"Account: %#", [item objectAtIndex:2]);
Alternatively you can go by keys and pull the array from "MailAccounts" first using valueForKey: (which will yield NSArray*) and then objectAtIndex: to get the dictionary of that particular account (useful if you need more than the name).

Two things:
You don't want or need to use NSBundle to get the path to the file. The file lies outside of the app bundle. So you should just have
NSString *plistPath = #"~/Library/Preferences/com.apple.mail.plist";
You have to expand the tilde in the path to the user directory. NSString has a method for this. Use something like
NSString *plistPath = [#"~/Library/Preferences/com.apple.mail.plist" stringByExpandingTildeInPath];

Related

Failed attempt using Related Items to create backup file in sandboxed app

The App Sandbox design guide says:
The related items feature of App Sandbox lets your app access files
that have the same name as a user-chosen file, but a different
extension. This feature consists of two parts: a list of related
extensions in the application’s Info.plist file and code to tell the
sandbox what you’re doing.
My Info.plist defines a document type for .pnd files (the user-chosen file), as well as a document type for .bak files. The entry for the .bak files has, among other properties, the property NSIsRelatedItemType = YES.
I am trying to use Related Items to move an existing file to a backup file (change .pnd suffix to .bak suffix) when the user writes a new version of the .pnd file. The application is sandboxed. I am not proficient with sandboxing.
I am using PasteurOrgManager as the NSFilePresenter class for both the original and backup files:
#interface PasteurOrgData : NSObject <NSFilePresenter>
. . . .
#property (readonly, copy) NSURL *primaryPresentedItemURL;
#property (readonly, copy) NSURL *presentedItemURL;
#property (readwrite) NSOperationQueue *presentedItemOperationQueue;
#property (readwrite) NSFileCoordinator *fileCoordinator;
. . . .
- (void) doBackupOf: (NSString*) path;
. . . .
#end
The doBackupOf: method is as follows. Notice that it also sets the NSFilePresenter properties:
- (void) doBackupOf: (NSString*) path
{
NSError *error = nil;
NSString *appSuffix = #".pnd";
NSURL *const pathAsURL = [NSURL URLWithString: [NSString stringWithFormat: #"file://%#", path]];
NSString *const baseName = [pathAsURL lastPathComponent];
NSString *const prefixToBasename = [path substringToIndex: [path length] - [baseName length] - 1];
NSString *const baseNameWithoutExtension = [baseName substringToIndex: [baseName length] - [appSuffix length]];
NSString *backupPath = [NSString stringWithFormat: #"%#/%#.bak", prefixToBasename, baseNameWithoutExtension];
NSURL *const backupURL = [NSURL URLWithString: [NSString stringWithFormat: #"file://%#", backupPath]];
// Move backup to trash — I am sure this will be my next challenge
// (it's a no-op now because there is no pre-existing .bak file)
[[NSFileManager defaultManager] trashItemAtURL: backupURL
resultingItemURL: nil
error: &error];
// Move file to backup
primaryPresentedItemURL = pathAsURL;
presentedItemURL = backupURL;
presentedItemOperationQueue = [NSOperationQueue mainQueue];
[NSFileCoordinator addFilePresenter: self];
fileCoordinator = [[NSFileCoordinator alloc] initWithFilePresenter: self]; // error here
[self backupItemWithCoordinationFrom: pathAsURL
to: backupURL];
[NSFileCoordinator removeFilePresenter: self];
fileCoordinator = nil;
}
The backupItemWithCoordinationFrom: method does the heavy lifting, basically:
[fileCoordinator coordinateWritingItemAtURL: from
options: NSFileCoordinatorWritingForMoving
error: &error
byAccessor: ^(NSURL *oldURL) {
[self.fileCoordinator itemAtURL: oldURL willMoveToURL: to];
[[NSFileManager defaultManager] moveItemAtURL: oldURL
toURL: to
error: &error];
[self.fileCoordinator itemAtURL: oldURL didMoveToURL: to];
}
but the code doesn't make it that far. I have traced the code and the URL variables are as I expect, and are reasonable. At the point of "error here" in the above code, where I allocate the File Presenter, I get:
NSFileSandboxingRequestRelatedItemExtension: an error was received from pboxd instead of a token. Domain: NSPOSIXErrorDomain, code: 1
[presenter] +[NSFileCoordinator addFilePresenter:] could not get a sandbox extension. primaryPresentedItemURL: file:///Users/cope/Me.pnd, presentedItemURL: file:///Users/cope/Me.bak
Any help is appreciated.
(I have read related posts Where can a sandboxed Mac app save files? and Why do NSFilePresenter protocol methods never get called?. I have taken note of several other sandboxing-related posts that don't seem relevant to this issue.)
MacBook Pro, MacOS 10.13.5, XCode Version 9.3 (9E145)
do not read too much about avoiding sandboxing. Most explenations go too far out of the most obvious problem. Instead of explaining the pitfalls that rightfully triggers sandboxing they explain mostly how to avoid the Sandbox at all. Which is not a solution - it is a thread!
So the most obvious problem is exposing a URL to pasteboard that still needs properly escaped characters in the string before you transform to NSURL.
So your NSString beginning with "file://" should use something like..
NSString *encodeStringForURL = [yourstring stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
before you transform to NSURL with
NSURL *fileurl = [NSURL URLWithString:encodeStringForURL];
NString *output = fileurl.absoluteString;

NSUserDefaults: how to get only the keys I've set

All of the methods to get keys from NSUserDefaults return heaps of keys from domains other than the app itself (e.g., NSGlobalDomain). I just want the keys and values that my app has set. This is useful for debugging and verifying that there are no orphaned keys, etc.
I could ignore the keys that aren't mine (if I know all of them -- during development I may have set keys I'm no longer using), but there might be a collision of keys in other domains and I'll not see my app's value.
Other discussions suggest looking at the dictionary file associated with the app, but that's not very elegant.
How can I get only my app's keys form NSUserdefaults?
Elegant approach
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
NSDictionary *dict = [defaults persistentDomainForName:bundleIdentifier];
File approach:
NSString *bundleIdentifier = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleIdentifier"];
NSString *path = [NSString stringWithFormat:#"~/Library/Preferences/%#.plist",bundleIdentifier];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[path stringByExpandingTildeInPath]];
NSArray *keys = [dict allKeys];
Tested with sandboxing.
Marek's code updated to Swift 5:
guard let bundleIdentifier = Bundle.main.bundleIdentifier else { return }
let dict = UserDefaults.standard.persistentDomain(forName: bundleIdentifier)

Read plist into nsmutabledictionary, update the dictionary and then save it again

I am really new to saving files in objective C but what I'm trying to accomplish is reading a plist file located in the documents directory on launch or creating it if it doesn't exist.
It should be read in to a NSMutableDictionary. Later on in the app I should be able to save items to the NSMutableDict with categories as keys + text.
The before launch in the viewWillUnload the NSMutableDictionary should be saved into the plist file again.
I have created the plist but I need a way to write to the NSMutableDictionary the right way (category and my result.text string.
And I also need to save the NSMutableDictionary to the plist file and read the plist into the dictionary on launch.
Some help with this would be awsome :D
Thanks guys.
In the savefile void I am doing this:
storeDict = [[ NSMutableDictionary alloc]
init];
[storeDict setObject:resultText.text forKey:#"kvitto"];
[storeDict setObject:kategori forKey:#"kategori"];
[storeDict writeToFile:[self saveFilePath] atomically:YES];
saveFilePath looks like this:
- (NSString *) saveFilePath {
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [[path objectAtIndex:0] stringByAppendingString:#"savefile.plist"];
}
The values are strings collected from a code that the user have scanned so don't worry bout them.
Well so how do I save this correctly keeping the data that already exists in the savefile.plist.
Thanks again
If you want dictionaries and arrays contained in the dictionary to be mutable as well then do the following:
NSData *data = [NSData dataWithContentsOfFile:path];
NSError *error;
storeDict =
[NSPropertyListSerialization
propertyListWithData:data
options:NSPropertyListMutableContainersAndLeaves
format:nil
error: &error];
Why can't you use writeToFile api? Before writing question here you must google or check apple documentation for NSMutableDictionary.
[dict writeToFile:path atomically:YES];
To load saved dictionary
dict = [NSMutableDictionary dictionaryWithContentsOfFile:path];
Happy coding!

How to get the path/directory component from a NSURL?

I retrieved a NSURL from a NSSavePanel. I now have this NSURL which gives me the following:
file://localhost/Users/brett/Documents/asdf%20asdf.json
Now, it is easy for me to retrieve just the filename using something like the following:
[[[NSFileManager defaultManager] displayNameAtPath:pathAndFilename] stringByDeletingPathExtension]
This gives me just the localized filename, as expected: asdf%20asdf
So, how do I get the path, like so: file://localhost/Users/brett/Documents/
-[NSURL URLByDeletingLastPathComponent] is the simplest way to achieve this.
You could use NSString methods to work with file paths. For example,
NSString *directory = [[URL absoluteString] stringByDeletingLastPathComponent];
NSString *filename = [[URL absoluteString] lastPathComponent];
You could find other useful methods in Apple Docs: NSString Class Reference -> Working with Paths section
Directly from your NSSavePanel:
NSSavePanel *savePanel;
...
NSString *path = savePanel.directoryURL.path;

Reading desktop plist

I am using following code to read the details of the plist,
NSString *plistPath = #"~/Library/Preferences/com.apple.desktop.plist";
NSDictionary *plistData = [NSDictionary dictionaryWithContentsOfFile:plistPath];
But plistData has no entries.
Is there something wrong in above code?
You need expanding the tilde. Try this:
NSString * plistPath = [#"~/Library/Preferences/com.apple.desktop.plist" stringByExpandingTildeInPath];

Resources