Search code examples
cocoa-touchfile-ioios-simulator

How to determine a file's Unicode character encoding in IOS?


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 ?


Solution

  • 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
            }
        }
    }