8

I need to open a NSSavePanel with the users Library folder as destination folder. Normally I would do this by entering ~/Library/ in [NSSavePanel beginSheetForDirectory].

This works fine as long as the application is not sandboxed. For sandboxed applications this will result in the NSSavePanel trying to access a folder inside the applications document "box".

I cannot refer to /Users/username/Library/ as I do not know the users username at runtime. So how do I link to this path in cocoa?

idmean
  • 14,540
  • 9
  • 54
  • 83
Øystein
  • 1,163
  • 1
  • 12
  • 23
  • If all you want to do is find the user's home dir see https://stackoverflow.com/questions/6958448/can-i-get-the-current-users-home-directory-in-a-cocoa-objective-c-application – sashoalm Feb 13 '15 at 16:58

3 Answers3

12

I'm not sure how sandboxing fits in with this, but you can find the user's library directory using:

NSArray* paths = NSSearchPathForDirectoriesInDomains( NSLibraryDirectory, NSUserDomainMask, YES );
JWWalker
  • 22,385
  • 6
  • 55
  • 76
2

Not sure if this will work on a sandboxed application but this is how I do it right now. This will return /User/TheirUserName

-(NSString *)homeDirectory
{
    return NSHomeDirectory();
}
syclonefx
  • 2,830
  • 1
  • 21
  • 24
  • 1
    `NSHomeDirectory()` returns in-sandbox path, at least on 10.7.4. However, while this is the proper method for getting a HOME folder, this is the improper way to fetch the LIBRARY folder. What if the path changes? Please use JWWalker's solution of `NSSearchPathForDirectoriesInDomains()`. Iterate over all returned elements whenever possible. – Ivan Vučica Jun 28 '12 at 09:23
0

It depends what you are trying to achieve.

  • If the behavior is required by your application, then you can request a temporary exception entitlement when submitting the application to the Mac App Store. But sooner or later, you will have to find a solution to remove this exception.
  • If you want to access data that were previously stored in the ~/Library/ folder, you can define a migration strategy to move back the data into the sandbox.
Laurent Etiemble
  • 27,111
  • 5
  • 56
  • 81
  • I do not need any elevated entitlements to achive this. It is enough to have read/write on the file system, as I use a save dialog to do the actual saving. I have run a proof of concept on this and know that works. What I need the user to do, is to save some files in this folder. That is why I need the actual folder and not just access to it's content. So it is no good to bring the data into my sandbox either. So I need some kind of way to read the users "username" to be able to build up the path to his Library folder, like: "~/user/[username]/Library/ – Øystein Nov 04 '11 at 07:19