【问题标题】:Permissions error renaming a file on disk重命名磁盘上的文件的权限错误
【发布时间】:2021-10-28 06:56:01
【问题描述】:

我正在尝试从 swift MacOS 应用程序重命名本地硬盘上的文件。

基本上我会打开打开的面板来选择文件所在的文件夹。然后我枚举文件并将它们重命名为修改日期。

以下是相关代码:

let openPanel = NSOpenPanel()
openPanel.canChooseDirectories = true
openPanel.canChooseFiles = false
openPanel.canCreateDirectories = false
openPanel.allowsMultipleSelection = false

var mtsVideosFolderPathString : String! = ""
if openPanel.runModal() == NSApplication.ModalResponse.OK
{
    mtsVideosFolder = openPanel.urls[0] as URL
    mtsVideosFolderPathString = mtsVideosFolder?.path

    let fileManager = FileManager.default
    let enumerator = fileManager.enumerator(atPath: mtsVideosFolderPathString)
    while let element = enumerator?.nextObject() as? String
    {
        if element.hasSuffix("MTS")
        {
            let filePath = "\(mtsVideosFolderPathString!)/\(element)"
            let fileModDate = self.fileModificationDate(url: URL(fileURLWithPath: filePath))

            let format = DateFormatter()
            format.timeZone = .current
            format.dateFormat = "yyyy.MM.dd HH.mm.ss"
            let dateString = format.string(from: fileModDate!)

            let fromFilename = "\(mtsVideosFolderPathString!)/\(element)"
            let toFilename = "\(mtsVideosFolderPathString!)/\(dateString).mts"
            print("Rename \(fromFilename) to \(toFilename)")

            do {
                try fileManager.moveItem(at: URL(fileURLWithPath: fromFilename), to: URL(fileURLWithPath: toFilename))
            }
            catch let error as NSError
            {
                print("Ooops! Something went wrong: \(error)")
            }
        }
    }
}

当我运行应用程序时,它在 try/catch 中的 moveItem 处失败,并出现以下错误:

Rename /Volumes/BigNFast/test/00000.mts to /Volumes/BigNFast/test/2013.08.05 20.09.50.mts
Ooops! Something went wrong: Error Domain=NSCocoaErrorDomain Code=513 "“00000.mp4” couldn’t be moved because you don’t have permission to access “ test”." UserInfo={NSSourceFilePathErrorKey=/Volumes/BigNFast/test/00000.mp4, NSUserStringVariant=(
    Move
), NSDestinationFilePath=/Volumes/BigNFast/test/2013.08.05 20.09.50.mp4, NSFilePath=/Volumes/BigNFast/test/00000.mp4, NSUnderlyingError=0x6000002bb450 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

那么,问题是,我该如何设置权限?如何重命名磁盘上的文件?

感谢您的帮助

【问题讨论】:

  • Swift 是一种类型推断语言。 if openPanel.runModal() == .OK {。顺便说一句,将 URL 转换为 URL 是没有意义的,这将为每个文件 URL 创建一个新的 DateFormatter

标签: swift xcode macos


【解决方案1】:

签名和功能 -> 文件访问 -> 用户选择的文件 使用选择器将其更改为读写。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 2020-06-01
    • 2019-07-07
    • 2017-11-14
    • 2012-08-18
    • 2020-03-18
    • 1970-01-01
    相关资源
    最近更新 更多