如何在 iOS 中的应用程序目录中创建目录?

How is it possible to create directories inside your application directory in iOS?

我试图在我的应用程序目录中创建一个目录,但出现以下错误:

Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “Some” in the folder “97391D11-283C-49FA-9A2B-8F8E2BBD89EE”." UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/97391D11-283C-49FA-9A2B-8F8E2BBD89EE/Some/, NSUnderlyingError=0x2819c2df0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}: file VocalTraineriOS/VocalTrainerApp.swift, line 37

这是我的代码:

try! FileManager.default.createDirectory(atPath: NSHomeDirectory() + "/Some/", withIntermediateDirectories: true)

您可以尝试在 .documentDirectory 中创建一个文件夹,如下所示。

do {
    let fileManager = FileManager.default
    let documentsDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let someFolderURL = documentsDirectory.appendingPathComponent("Some")
    try fileManager.createDirectory(at: someFolderURL, withIntermediateDirectories: true, attributes: nil)
    print(someFolderURL)
} catch {
    print(error)
}

文档目录 URL 具有这种格式 -

"file:///var/mobile/Containers/Data/Application/FB12D808-9054-4799-9C69-115ACD805A24/Documents/"