How to read GB2312 encoded text files using Swift

2019-09-08 10:46发布

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条回答
等我变得足够好
2楼-- · 2019-09-08 11:15

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)
查看更多
登录 后发表回答