How to read GB2312 encoded text files using Swift

2019-09-08 11:19发布

问题:

My app needs to read text files encoded in GB2312. Here is the current code.

 SGFString = try String(contentsOf:path)

It throws an exception.

couldn’t be opened because the text encoding of its contents can’t be determined.

While looking into the String.Encoding values, there is no GB2312. What would be the best way to read the GB2312 text files?

Thanks Ray

回答1:

Thanks for OOPer's help. I copied some of the code from the links, now it works. Here is the code:

extension String.Encoding {
    static let gb_18030_2000 = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue)))
}

Gb2312String =  try String(contentsOf:path, encoding:String.Encoding.gb_18030_2000)