Wackerflacker Wackerflacker -3 years ago 126
Swift Question

Read text file from network URL

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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download