2

My code currently looks like

import UIKit

if let url = URL(string: "https://s3.eu-west-2.amazonaws.com/sliptip/test.rtf") {
    do {
        let contents = try String(contentsOf: url)
        print(contents)
    } catch {
        // contents could not be loaded
    }
} else {
    // the URL was bad!
}

and returns a lot of jargon,

\f0\fs24 \cf0 NEW Newcastle 84 }

but all I want is the contents without the characters before and after.

Ideally it should just print

 NEW Newcastle 84
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Wackerflacker
  • 31
  • 1
  • 7

1 Answers1

0

The .rtf extension on your URL tells me that the file contains Rich Text Format (RTF), which means it has formatting markup mixed in with the text.

If you are on an Apple platform, you can use the platform's RTF parser to load the file as an NSAttributedString and get the plain text from it:

let richText = try NSAttributedString(url: url, options: [:], documentAttributes: nil)
let plainText = richText.string
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • 1
    I had the same idea, but apparently it doesn't support `https`, I got the following error when trying to download the `.rtf` file using `NSAttributedString`: "Error Domain=NSCocoaErrorDomain Code=262 "The file “test.rtf” couldn’t be opened because URL type https isn’t supported." UserInfo={NSURL=https://s3.eu-west-2.amazonaws.com/sliptip/test.rtf}\n" – Dávid Pásztor Aug 16 '17 at 15:03
  • Changing the original file to .txt worked, and displayed as it should. Thank you – Wackerflacker Aug 16 '17 at 15:03