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

时间:2017-09-01 04:19:12

标签: ios swift nsfilemanager

我正在尝试在Application Support Directory中创建一个目录,但每次都会失败。

以下是代码:

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

我已经尝试更改追加路径组件,尝试了文档目录,所有失败都有相同的错误。

1 个答案:

答案 0 :(得分:3)

问题出在这一行

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

返回 filePath,而下面的函数需要目录的简单路径

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)

希望这会对你有所帮助。