Reputation: 3454
I am trying to rename a file on the local hard disk from a swift MacOS application.
Basically I am bringing up the open panel to select the folder where the files are. then I enumerate the files and rename them to the modification date.
Here is the relevant code:
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)")
}
}
}
}
When I run the app its fails at moveItem in the try/catch with the following error:
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"}}
So, the question is, how do I set the permissions? How to I rename a file on disk?
Thank you for any help
Upvotes: 0
Views: 154
Reputation: 758
Signing and Capabilities -> File Access -> User Selected File Change it to read and write with the selector.
Upvotes: 2