Kevin
Kevin

Reputation: 244

Permission Denied when trying to create a directory in Application Support

I'm trying to create a directory inside the Application Support Directory, but it fails every single time.

Here's the code:

func getDownloadableContentPath() -> String {
        let paths = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true)
        var directory = paths[0]
        directory = URL(fileURLWithPath: directory).appendingPathComponent("IAP").absoluteString
        let fileManager = FileManager.default
        if !fileManager.fileExists(atPath: directory) {
            do {
               try fileManager.createDirectory(atPath: directory, withIntermediateDirectories: true, attributes: nil)
            }
            catch {
               print("Error: Unable to create directory: \(error)")
            }
            var url = URL(fileURLWithPath: directory)
            var values = URLResourceValues()
            values.isExcludedFromBackup = true
            do {
                try url.setResourceValues(values)
            }
            catch {
                print("Error: Unable to exclude directory from backup: \(error)")
            }
        }
        return directory
    }

The Error is:

 Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “IAP” in the folder “Application%20Support”." UserInfo={NSFilePath=file:///var/mobile/Containers/Data/Application/FF91E234-F856-492E-8C91-9EFAEA3735D4/Library/Application%20Support/IAP, NSUnderlyingError=0x174245430 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

I've tried changing the appending path component, tried the documents directory, all fail with the same error.

Upvotes: 1

Views: 4035

Answers (1)

Surjeet Singh
Surjeet Singh

Reputation: 11939

The problem is in this line

directory = URL(fileURLWithPath: directory).appendingPathComponent("IAP").absoluteString

This return filePath, while below function required simple path of directory.

fileManager.createDirectory(atPath: directory, withIntermediateDirectories: true, attributes: nil)

So either change this line

directory = URL(fileURLWithPath: directory).appendingPathComponent("IAP").absoluteString

with this line

directory = directory + "/IAP"

OR change same line with below line

let url = URL(fileURLWithPath: directory).appendingPathComponent("IAP")

and use this function to create directory

fileManager.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)

Hope this helps you.

Upvotes: 6

Related Questions