Search code examples
swift4xcode9

Get user desktop path in Swift 4.0 and Xcode 9.0


I am trying to get the path to the desktop of the current user, but I get a path to another location in the library (see code).

The same code in Playgrounds gives the right answer. I used the same code in an earlier created project version of Xcode and that gives also the good results.

The tests are done under MacOS High Sierra, Xcode Version 9.0 (9A235) and Swift 4.0.

Here is the code used:

public func userDesktop() -> String {
  let paths = NSSearchPathForDirectoriesInDomains(.desktopDirectory, .userDomainMask, true)
  let userDesktopDirectory = paths[0]
  return userDesktopDirectory
}

let myPath:String = userDesktop() + "/"
print(myPath)

let userDesktopDirectory:String = NSHomeDirectory() + "/" + "Desktop/"
print(userDesktopDirectory)

/* results in Playground */
/Users/kader/Desktop/
/Users/kader/Desktop/

/* Results from a project in Xcode 9.0 */
/Users/kader/Library/Containers/com.kader.testuserpath/Data/Desktop/
/Users/kader/Library/Containers/com.kader.testuserpath/Data/Desktop/

What is wrong about this code or is it a bug?

I am curious whether more people have experienced the same problem.


Solution

  • I noticed that the Cocoa Application template in Xcode 9 turns on App Sandbox by default. With this mode on, the app is restricted to access files within its own container, just like iOS apps. You can turn it off in the Capabilities tab in your project settings. A screenshot from Apple's documentation:

    Capabilities

    What your app can do inside a sandbox. If you are doing this for fun, have no intention of distributing it through the Mac App Store, or want a "computer application" in the traditional sense of the words, turn off sanboxing altogether. It has long been the pain of the Mac App Store and the reason that many developers are leaving the store.