Accessing applicationDocumentsDirectory

I'm reading this (good) post from SO to implement bookmarks for security scoped URL.


h ttps://stackoverflow.com/questions/31278869/file-access-in-a-sandboxed-osx-app-with-swift


At the beginning, they have :

func bookmarkPath() -> String {
    var url = app.applicationDocumentsDirectory
    url = url.appendingPathComponent("Bookmarks.dict")
    return url.path
}


I cannot figure out how app is defined. Is it the appDelegate ? Its controller ? I've tried many variations unsuccessfully.

How should I define app ?


I ended up replacing

    var url = app.applicationDocumentsDirectory

by :

     var url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL


Is that equivalent ?

Accepted Reply

I cannot find any classes which have a property `applicationDocumentsDirectory`. But in many sample codes of Apple, this sort of method is defined:

- (NSURL *)applicationDocumentsDirectory
{
  return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}


In Swift:

    var applicationDocumentsDirectory: URL {
        return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
    }

So, your code is very near and should work the same.

Replies

I cannot find any classes which have a property `applicationDocumentsDirectory`. But in many sample codes of Apple, this sort of method is defined:

- (NSURL *)applicationDocumentsDirectory
{
  return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}


In Swift:

    var applicationDocumentsDirectory: URL {
        return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
    }

So, your code is very near and should work the same.

Hi there,


And how can I read the files in that selected folder? A code example.
Because print("Restoring \(bookmark.key)") show me only the URL

You'd better start a new thread for your own. Generally, a new thread can get much more attension than a thread marked as solved.


And just showing a small code fragment does not make sense. Include enough info to describe your issue including all relevant codes.

Or do you think all readers take their time to find where that small fragment exists on the web?

OK, I created a new post.

https://forums.developer.apple.com/message/251864#251864