2

In our application I have to open a text file which will be sum time UTF-8 format or UTF-16 format .

Is there any way to determine the file format of a file? Or Is it possible to check the readied 'NSString' is valid ?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Eldhose
  • 726
  • 8
  • 19

2 Answers2

1

You can use the following do-catch blocks as stated in the documentation if you are forced to guess the encoding of your text file, which works for Swift 4.0:

do {
    let str = try String(contentsOf: url, usedEncoding: &encodingType)
    print("Used for encoding: \(encodingType)")
} catch {
    do {
        let str = try String(contentsOf: url, encoding: .utf8)
        print("Used for encoding: UTF-8")
    } catch {
        do {
            let str = try String(contentsOf: url, encoding: .isoLatin1)
            print("Used for encoding: Windows Latin 1")
        } catch {
            // Error handling
        }
    }
}
MosTwanTedT
  • 323
  • 3
  • 12
0

Apple's documentation has some guidance on how to proceed: String Programming Guide: Reading data with an unknown encoding:

If you are forced to guess the encoding (and note that in the absence of explicit information, it is a guess):

Try stringWithContentsOfFile:usedEncoding:error: or initWithContentsOfFile:usedEncoding:error: (or the URL-based equivalents). These methods try to determine the encoding of the resource, and if successful return by reference the encoding used.

If (1) fails, try to read the resource by specifying UTF-8 as the encoding.

If (2) fails, try an appropriate legacy encoding. "Appropriate" here depends a bit on circumstances; it might be the default C string encoding, it might be ISO or Windows Latin 1, or something else, depending on where your data is coming from.

Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
Gabrail
  • 216
  • 2
  • 16