How to create a directory in downloads folder with swift on macos? Permission exception.
Xcode 9 and later enables sandboxing by default, which severely limits interactions with the system. However you can still write to the Downloads folder by adding an entitlement to your app:
Select your target, then Capabilities and set Downloads Folder to Read/Write:
If you have no intention of distributing your app through the Mac App Store, you can turn off sandboxing. Your application can still be signed but users will get a warning when they first launch your app.
Open Downloads Directory With Finder Prompting User for Permission If Necessary
I am assuming you want this all to play nicely within the sandbox. You have two choices:
Use
activateFileViewerSelecting(_:)
orselectFile(_:inFileViewerRootedAtPath:)
. Either of these will prompt for permission, & once gained, you can return to usingopen(_:withApplicationAt:configuration:completionHandler:)
, if you so wish.Use Security-Scoped Bookmarks and Persistent Resource Access.
How would I check for a file in a specified directory in Swift 5?
Figured it out. Here's what I put for Swift 5.
let path = NSString(string: "~/test-node.js").expandingTildeInPath
let fileDoesExist = FileManager.default.fileExists(atPath: path)
The "~/test-node.js" should be replaced with the path of the file you want to verify exists.
Read and write permission for user selected folder in Mac OS app?
Add user-selected
and bookmarks.app
permissions in entitlement file :
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
<key>com.apple.security.files.bookmarks.app-scope</key>
<true/>
Then open folder selection using NSOpenPanel
so the user can select which folders to give you access to. The NSOpenPanel
must be stored as a bookmark and saved to disk. Then your app will have the same level of access as it did when the user selected the folder.
Writing to the downloads folder in a sandboxed app
The App-Identifier
will be the Bundle ID. As to where this restriction to write to a subfolder of ~/Downloads
comes from I've no idea (it does not appear to be in the Review Guidelines, the App Sandbox Guide, etc. as you found out). You could query the review, but going another way might be easier...
You will probably be better off using a bookmark, see Security-Scoped Bookmarks and Persistent Resource Access, and an entitlement as your linked question suggests. This will also allow you to directly store into ~/Downloads
without question - if the user selects it (put up a standard file dialog styled as a permission request, only allow folders, and preset to show the home directory; you can if you wish restrict selection to only Downloads).
HTH
Error: You don’t have permission to save the file in the folder
Thanks to this post I realized its because of this line:
let destString = destPath.absoluteString
I had to change it to:
let destString = documentsURL.relativePath
Which allowed me to greatly simplify my function:
static func unzipFile(atPath path: String) -> Bool
{
let destString = documentsURL.relativePath
let success: Void? = try? SSZipArchive.unzipFile(atPath: path, toDestination: documentsURL.relativePath, overwrite: true, password: nil)
if success == nil
{
return false
}
return true
}
How to create directory using Swift code (NSFileManager)
Swift 5.0
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let docURL = URL(string: documentsDirectory)!
let dataPath = docURL.appendingPathComponent("MyFolder")
if !FileManager.default.fileExists(atPath: dataPath.path) {
do {
try FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error.localizedDescription)
}
}
Swift 4.0
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentsDirectory: AnyObject = paths[0] as AnyObject
let dataPath = documentsDirectory.appendingPathComponent("MyFolder")!
do {
try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
}
Swift 3.0
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentsDirectory: AnyObject = paths[0]
let dataPath = documentsDirectory.appendingPathComponent("MyFolder")!
do {
try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
}
Swift 2.1
You can create directory using below method:
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDirectory: AnyObject = paths[0]
let dataPath = documentsDirectory.stringByAppendingPathComponent("MyFolder")
do {
try NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
}
Create a folder inside documents folder in iOS apps
I do that the following way:
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
Related Topics
Swift Generics: Non-Nominal Type Does Not Support Explicit Initialization
Dynamic Datasource/Delegates for Uitableview in Swift
Resizing Uimage When Using Sf Symbols - Uiimage(Systemname:)
Take a Full Screenshot for All Webview in Swift
How to Use View Controller (Calendarkit) in Swiftui Application
Xcode: Using Custom Fonts Inside Dynamic Framework
Observe Progress of Data Download in Swift
Swift 3: Int Is Not Convertible to Bool in Bitwise Operation
Round Currency Closest to Five
Swift Radio Streaming Avplayer
Enum Not Working in Custom Initializer
Swift 2.2, Contains Method Not Working
Codable/Decodable Should Decode Array with Strings
Swiftui List View Not Updating After Core Data Entity Updated in Another View
Swift: Uploading Image to Firebase Cloud Storage When User Closes App
Swift ? Must Be Followed by a Call, Member Lookup, or Subscript