How do you read data from a text file in Swift 3 (XCode 8)

前端 未结 1 1521
傲寒
傲寒 2021-01-13 17:49

first I would like to start with my current situation:

1) Current Situation:

I have a text file (data.rtf) I have also tried and am willing to use .plist or

1条回答
  •  清酒与你
    2021-01-13 18:01

    The main issue is that you cannot load rich text (RTF) formatted text into String. The Cocoa equivalent to RTF is NSAttributedString.

    Load the RTF as Data, create an NSAttributedString and get the plain text with the string property.

    var arrayClients = [[String:String]]() // do not use NSMutableArray in Swift
    var dictClients = [String:String]()
    
    if let url = Bundle.main.url(forResource:"data", withExtension: "rtf") {
        do {
            let data = try Data(contentsOf:url)
            let attibutedString = try NSAttributedString(data: data, documentAttributes: nil)
            let fullText = attibutedString.string
            let readings = fullText.components(separatedBy: CharacterSet.newlines)
            for line in readings { // do not use ugly C-style loops in Swift
                let clientData = line.components(separatedBy: "\t")
                dictClients["FirstName"] = "\(clientData)"
                arrayClients.append(dictClients)
            }
        } catch {
            print(error)
        }
    }
    

    However for that kind of data structure RTF is not appropriate. Better use JSON or property list.

    0 讨论(0)
提交回复
热议问题