Manipulating files outside of sandbox

:  ~ 1 min read

First, we need to ask for the user's permission to access the folder, but for that, we need an NSOpenPanel:

let op = NSOpenPanel()
op.message = "Descriptive message here"
op.canCreateDirectories    = false
op.canChooseDirectories    = false
op.showsHiddenFiles        = false
op.prompt                  = "Allow"
op.title                   = "Allow access"
op.extensionHidden         = true
op.directoryURL            = NSURL(string: "/path/to/folder")

// Depending on your purpose, you might need these to true
op.allowsMultipleSelection = false
op.canChooseFiles          = false

We then check if the panel's URL matches the one we need, and save a secure scoped bookmark in user defaults, for example:

guard op.runModal() == NSFileHandlingPanelOKButton && openPanel.URL == requiredURL else {

	let bookmarkData = try? requiredURL.bookmarkDataWithOptions(.WithSecurityScope,
		includingResourceValuesForKeys: nil,
		relativeToURL: nil)
	where bookmarkData != nil
	else { return }
NSUserDefaults.standardUserDefaults().setObject(bookmarkData, forKey: requiredURLKey)

From now on, when we need access to this location, we can just resolve the data saved back into an NSURL, and use it; we just need to check if the bookmark staled in the meantime:

var staleBookmark: ObjCBool = false
	let bookmarkData = NSUserDefaults.standardUserDefaults()
	let url = try? NSURL(byResolvingBookmarkData: bookmarkData,
		options: .WithSecurityScope,
		relativeToURL: nil,
		bookmarkDataIsStale: &staleBookmark
	else { return }
guard !staleBookmark else { return }

// Code for using the URL.