在Swift的Application Support中创建嵌套目录

时间:2018-06-22 08:19:26

标签: ios swift file-manager

尝试在应用程序支持内创建嵌套目录,但失败。我收到的错误消息是"You don’t have permission to save the file 'folder1' in the folder 'testApp'

    let path = getApplicationSupportDirectory()
    let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as! String
    let folder = path.appendingPathComponent("\(appName)/folder1", isDirectory: true)
    print("[ERR]: Folder location: \(folder.relativePath)")
    if !FileManager.default.fileExists(atPath: folder.relativePath) {
        do {
            try FileManager.default.createDirectory(atPath: folder.relativeString, withIntermediateDirectories: true, attributes: nil)
        } catch {
            print("[ERR]: \(error.localizedDescription)")

        }
    }

文件夹位置输出正确的位置,并且似乎在“ appName”中创建第一个目录。

1 个答案:

答案 0 :(得分:3)

请尝试使用此代码,它应该可以工作。

如果不存在,它将使用FileManager的API创建应用程序支持文件夹。

do {
    let applicationSupportFolderURL = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as! String
    let folder = applicationSupportFolderURL.appendingPathComponent("\(appName)/folder1", isDirectory: true)
    print("[ERR]: Folder location: \(folder.path)")
    if !FileManager.default.fileExists(atPath: folder.path) {
        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true, attributes: nil)
    }
} catch { print(error) }