jon
jon

Reputation: 131

Use swift and macOS to set file attributes

macOS, swift3
Apple has an API Foundation > FileManager > setAttributes(_:ofItemAtPath:)

The declaration is func setAttributes(_ attributes: [FileAttributeKey : Any], ofItemAtPath path: String) throws

It is for setting the creation date etc for a file. I can handle the >ofItem path:String) throws< but the first part has me stumped.

The API says it can return 'true' but swift returns void. There is an attribute named 'creationDate'. What is the significance of the underscore '_'.
I think 'attributes' is a mutable dictionary

 var myAttributesDictionary = [FileAttributeKey : Date]()
 myAttributesDictionary[FileAttributeKey.creationDate] = myDateObject

let fm = FileManger()
let xxx = fm.setAttributes(myAttributesDictionary:[FileAttributeKey : creationDate], ofItemAtPath myPath)

I have tried many variations and now I am stumped and I do not know what is required. I cannot get the setAttributes line to compile

Upvotes: 1

Views: 890

Answers (1)

jon
jon

Reputation: 131

I spent some time looking for an answer before posting the question. When I went looking for my questionI found an answer.

let mypath = "/path/to/file"
let myDateObject = NSDate()       // NSDate()  is todays date

let attributes = [FileAttributeKey.creationDate: myDateObject]

 do {
        try FileManager.default.setAttributes(attributes, ofItemAtPath: myPath)
  } 
  catch 
  {
        print(error)
  }

Upvotes: 1

Related Questions