尝试在应用程序支持中创建目录时权限被拒绝

Permission Denied when trying to create a directory in Application Support

我正在尝试在应用程序支持目录中创建目录,但每次都失败。

代码如下:

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
    }

错误是:

 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"}}

我试过更改附加路径组件,尝试文档目录,都失败并出现相同的错误。

问题出在这一行

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

这个return 文件路径,而下面的函数需要简单的目录路径

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

所以要么改变这一行

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

用这条线

directory = directory + "/IAP"

用下面的行更改同一行

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

并使用此函数创建目录

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

希望对您有所帮助。