2

To read a file into a string, I'm using the following:

let contents = try String(contentsOf: url)

I'm not specifying a particular encoding because, of course, the user could open any file with any encoding. Problem is, this works for some encodings and not others. Using file -I * in my directory or files, I realised that the files I'm trying this on are a mixture of us-ascii and iso-8859-1 files. When it attempts to read us-ascii files, it works, but it doesn't for iso-8859-1.

I suppose iso-8859-1 is less common or something, because Swift doesn't seem to be able to infer its encoding for me. Is there some way to make this work? Maybe using a library to detect encoding?

Zac
  • 813
  • 10
  • 22
  • There is a method which tries to *detect* the encoding, see https://stackoverflow.com/a/36079331/1187415 for an example, or https://stackoverflow.com/a/31442691/1187415 (which is Objective-C, but easily translated). – Martin R May 11 '18 at 17:20
  • That doesn't seem to help - for every file I try it says it's "Unicode (UTF-8)", but the same ones still throw an error saying "couldn't be opened because the text encoding of its contents can't be determined" – Zac May 11 '18 at 17:27
  • If everything else fails, try several encodings, until one succeeds. – Martin R May 11 '18 at 17:47

0 Answers0