prabhu prabhu - 1 year ago 132
iOS Question

Write extend file attributes swift example

I am looking for a solution to add extended file attributes for a file in swift. I checked this link Write extended file attributes, but the solutions are in objective c and I need a solution for swift.

Answer Source

A simple example:

let fileURL = NSURL(fileURLWithPath: "/path/to/file")
let attrName = "com.myCompany.myAttribute"
var attrData: [UInt8] = [1, 2, 3, 4, 5]

// Get local file system path:
var fileSystemPath = [Int8](count: Int(MAXPATHLEN), repeatedValue: 0)
guard fileURL.getFileSystemRepresentation(&fileSystemPath, maxLength: fileSystemPath.count) else {
    fatalError("Invalid file URL")

// Set extended attribute (returns 0 on success):
guard setxattr(&fileSystemPath, attrName, &attrData, attrData.count, 0, 0) == 0 else {
    perror("setxattr") // prints error message of last system call

Verify the result on the command line:

$ xattr -px com.myCompany.myAttribute /path/to/file 
01 02 03 04 05

Of course you can wrap that into an utility function which returns a Bool indicating success (or alternatively throws an error in the case of a failure).