ios - 由于文件 "does not exist",Swift MoveItem 失败

标签 ios swift

因此,我尝试重命名应用程序中的文件夹,但 moveItem 方法的行为很奇怪。这是我的代码:

try FileManager.default.moveItem(at: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("parentFolder").appendingPathComponent("folderIWantToMove"), to: FileManager.default.urls(for: .applicationDirectory, in: .userDomainMask)[0].appendingPathComponent("parentFolder").appendingPathComponent("newFolderName"))

此操作失败,调试器中的消息是:

“folderIWantToMove” couldn’t be moved to “parentFolder” because either the former doesn’t exist, or the folder containing the latter doesn’t exist.

但是当我在 lldb 中运行它时:

print FileManager.default.fileExists(atPath: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("parentFolder").appendingPathComponent("folderIWantToMove").path)

print FileManager.default.fileExists(atPath: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("parentFolder").path)

两者都返回 true,这意味着两个文件夹确实存在。我读过其他一些有类似问题的问题,大多数人说这是因为沙箱。如果是这种情况,我如何才能更改用户文档目录中的文件名称并删除文件?

为了以防万一,我使用的是 swift 5,并在装有 iPadOS 13(来自 Xcode 12 beta)的 iPad 上运行所有内容。

最佳答案

问题在于您没有重命名它,您正在尝试将目录从文档目录内部移动到应用程序目录,该目录不在您的 bundle 中,并且无法从 iOS 中的应用程序访问。

let document = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let parentFolder = document.appendingPathComponent("parentFolder")
let folderIWantToMove = parentFolder.appendingPathComponent("folderIWantToMove")
do {
    try FileManager.default.createDirectory(at: folderIWantToMove, withIntermediateDirectories: true, attributes: nil)
    print("folder and sub folder created")
    print("folderIWantToMove path:", folderIWantToMove.path)
    // renaming it
    let newFolderName = parentFolder.appendingPathComponent("newFolderName")
    try FileManager.default.moveItem(at: folderIWantToMove, to: newFolderName)
    print("folder renamed to:", newFolderName.path)
} catch {
    print(error)
}

关于ios - 由于文件 "does not exist",Swift MoveItem 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64851902/

相关文章:

Swift:从 flatMap 到字典

ios - 如何创建 UILabel 动态高度和布局 anchor 约束?

ios - 单击时 MapView 自定义图钉不显示详细信息

ios - 当应用程序使用 Facebook 登录时,SVProgressHud 未在 iOS 9 中显示

ios - 新的 NSManagedObject 子类与新的 NSObject 子类?

ios - FCNDEF消息查询NDEFStatusWithCompletionHandler :]: unrecognized selector sent to instance

ios - 获取文档目录中每个项目的属性 iOS Swift

swift - 如何在 Vapor 3 中将字典的元素分配给 JSON 对象?

ios - Swift 动画外壳不会动画

iphone - 手势在 UITableViewCell 的右侧不起作用