3

I searched a lot and couldn't find the answer. I just started using xcode and have a very very simple program named "Image Test".

---> It has a button, and a textField. I want to show my system home directory path in the textField. This is my code:

@IBOutlet weak var textField1: NSTextField!
@IBAction func Button1(_ sender: Any) {

    do{
        let home = try FileManager.default.homeDirectoryForCurrentUser
        textField1.stringValue = home.path
    }
    catch{}
}

it works but the returned path is like: /Users/myname/Library/Containers/com.Image-Test/Data

I have tested this code before in Xcode Playground and it was correct. Its the same code but not throwing the right path.

Vandad
  • 33
  • 5

1 Answers1

3

It's because of sandboxing. The documentation states:

The App Sandbox Container Directory

It is located at a system-defined path, within the user’s home directory. In a sandboxed app, this path is returned when your app calls the NSHomeDirectory function.

You can verify this by removing the App Sandbox capability (note: I am not suggesting that this is what you should do for your app).

PS: If you intend to submit your app to the AppStore, sandboxing must be enabled.

Alladinian
  • 34,483
  • 6
  • 89
  • 91
  • Thank you so much. yes it did work. I just started learning xcode and swift and doing tests. Thanks again – Vandad Sep 20 '19 at 15:26
  • 1
    @Vandad You're welcome. Please keep in mind that although disabling sandboxing might seem 'convenient' and ok while you're learning, it is something really important for any production app. – Alladinian Sep 20 '19 at 15:29
  • is this about hacking? and if sandbox is disabled, and if it works in my system, will it work in another system? does it recognize the home directory (or others) as on my system?! – Vandad Sep 20 '19 at 15:47
  • This is about security. The rationale behind this is that your app should only have access to whatever resource the _user_ decides to grant access and not the whole system. I believe that it would work on another system, provided that the user gives explicit permission (I could be wrong though; if anybody knows more about it I would be glad to know as well). You can read much more in the documentation link that I've included in my answer. – Alladinian Sep 20 '19 at 15:58
  • Thanks again. Specially for quick answer :)) – Vandad Sep 20 '19 at 16:09