How do you get path to user desktop in XCode?

11,273

Solution 1

You can specify the desktop in the search path:

NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDesktopDirectory, NSUserDomainMask, YES);
NSString * desktopPath = [paths objectAtIndex:0];

The advantage of doing it this way is that it makes no assumptions about how the user has configured his Mac, If his desktop folder isn't in the default location, this will still find the correct one.

Solution 2

This should work:

NSString *pathToDesktop = [NSString stringWithFormat:@"/Users/%@/Desktop/text.txt", NSUserName()];

Solution 3

I use this statement, it assumes that the Desktop folder is in the usual location.

[NSURL fileURLWithPath:[NSHomeDirectory()stringByAppendingPathComponent:@"Desktop"];
Share:
11,273
Just a coder
Author by

Just a coder

I love coding.

Updated on July 28, 2022

Comments

  • Just a coder
    Just a coder over 1 year

    I have tried:

    path = @"~/Desktop/files/text.plist";
    NSDictionary *aDict = [NSDictionary dictionaryWithContentsOfFile:path];
    

    ResultPath: ~/Desktop/files/text.plist

    path = @"$(HOME)/Desktop/files/text.plist";
    NSDictionary *aDict = [NSDictionary dictionaryWithContentsOfFile:path];
    

    ResultPath: $(HOME)/Desktop/files/text.plist

    path = [NSHomeDirectory() stringByAppendingString:@"/Desktop/files/text.plist"];
    NSDictionary *aDict = [NSDictionary dictionaryWithContentsOfFile:path];
    

    ResultPath: /Users/my_name/Library/Application Support/iPhone Simulator/5.1/Applications/639DC66A-7092-4ECB-9E48-59935AC1C394/Desktop/files/text.plist

    1. Is there any way to get to the User's desktop path in XCode?
    2. Can environment variables be used in the example above and how?

    EDIT: Further explanation on 2nd question: Just like there are environment variables (or Macros) in the MAC console, can these also be used within the code? If they can be used, can any one help with an example? like $HOME_DIRECTORY or something like that.