1

When you save an NSString (or Swift.String) using a method like this, it writes the xattr "com.apple.TextEncoding". When you load it back with one of the corresponding methods, it checks this xattr and uses that as the default encoding.

Is there any API to determine the encoding of a file, according to this xattr, without having to load the contents of the file?

I know it's not that hard to parse "IANA name, semicolon, CFString​Encoding uint32, (optional other stuff)", but I'd rather avoid it if there's a built-in way.

Ssswift
  • 916
  • 10
  • 20

1 Answers1

-1

If I understand your question correctly, you're asking for a way to read the value of the "com.apple.TextEncoding" extended file attribute. This is possible via API declared in <sys/xattr.h>.

Here's a post that extends URL with extended attributes capabilities: Write extend file attributes swift example

Example usage:

func getTextEncodingAttribute(for url: URL) -> String? {
    do {
        let data = try url.extendedAttribute(forName: "com.apple.TextEncoding")
        return String(data: data, encoding: .utf8)
    } catch _ {
    }
    return nil
}
  • That is how to read an xattr, yes, but it only gives the value as a String. As I stated in the question, the icky part is *parsing this value*: the (overly complex) "IANA name ; CFStringEncoding, blah blah" format. – Ssswift Sep 17 '17 at 17:04