如何从Swift 3(XCode 8)中的文本文件中读取数据

时间:2021-09-02 06:07:17

first I would like to start with my current situation:

首先,我想从目前的情况开始:

1) Current Situation:

1)现状:

I have a text file (data.rtf) I have also tried and am willing to use .plist or any other format to get a result.

我有一个文本文件(data.rtf)我也尝试过并且愿意使用.plist或任何其他格式来获得结果。

I have been trying to read ANY data from this file, and show that data on a Label.

我一直在尝试从该文件中读取任何数据,并在Label上显示该数据。

I have tried pre-populating the file, saving to the file before reading from it, and even just checking that the file exists, but every attempt has failed.

我已经尝试预先填充文件,在读取之前保存到文件中,甚至只检查文件是否存在,但每次尝试都失败了。

For 3 days I have searched various instructions and tutorials on how to do what is usually a fairly simple feature. I already did it using Objective-C, but I am new to Swift and unfortunately have to use it for this assessment and I am stuck.

在3天内,我搜索了各种指令和教程,了解如何做通常相当简单的功能。我已经使用Objective-C做了它,但我是Swift的新手,不幸的是我不得不用它进行评估而且我被卡住了。

2) Obstacles:

2)障碍:

Every example I have looked at so far has been rejected by XCode as erroneous, ether for using terms that are no longer accepted like:

我到目前为止所看到的每个例子都被XCode拒绝为错误的,因为使用了不再被接受的术语,如:

let path = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("image.png")

Or lines that flat out do not work at all like:

或者平坦的线条根本不起作用:

let client = arrayClients[0]
    DisplayLabel.text = "\(client.ob("FirstName")!) \(client.objectForKey("LastName")!)"
    //DisplayLabel.text = client.  <- this part doesn't work

Every case either ends with code that is too out of date to work, or is too butchered after updating it to the replacements recommended to still work. The only cases where I have got the code to even build (removing syntax errors) has logical errors where the results either are nothing, or it crashes, most commonly with:

每个案例都以过时的代码结束工作,或者在将其更新为建议仍然有效的替换后过于苛刻。我获得代码甚至构建(删除语法错误)的唯一情况有逻辑错误,其中结果是什么都没有,或者它崩溃,最常见的是:

"NSCocoaErrorDomain Code = 260 "The file "data.rtf" couldn't be opened because there is no such file." "No such file or directory"

“NSCocoaErrorDomain Code = 260”无法打开文件“data.rtf”,因为没有这样的文件。“”没有这样的文件或目录“

I think, even though the file exists in my XCode project, it is being searched for in the iPhone simulator, and for some reason it does not exist there. This is only a theory, and I have no idea how to fix that. I never encountered this problem when doing the same thing using Objective-C, where if I made a file and path to it, it worked, but for Swift it simply refuses to

我认为,即使该文件存在于我的XCode项目中,它仍在iPhone模拟器中进行搜索,并且由于某种原因它在那里不存在。这只是一个理论,我不知道如何解决这个问题。我在使用Objective-C做同样的事情时从未遇到过这个问题,如果我创建了一个文件和路径,它可以工作,但对于Swift,它只是拒绝

3) The Code:

3)守则:

At this point, I am more interested in a code that works, than a fix to mine that does not, as mine has become so butchered in my attempts to solve this (as well as other XCode update related issues) that it is barely fit for purpose even if I get around this obstacle, but in case it helps, I will provide "some" of the different attempts I have pulled

在这一点上,我对一个有效的代码更感兴趣,而不是一个不能修复的代码,因为我试图解决这个问题(以及其他XCode更新相关问题)已经变得如此拙劣,以至于它几乎不适合为了目的,即使我绕过这个障碍,但如果它有所帮助,我会提供“一些”我尝试的不同尝试

// The "file not found code" :

//“找不到文件代码”:

let path = (NSTemporaryDirectory() as NSString).appendingPathComponent("data.rtf")

    do {
        // Get the contents
        let contents = try NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue)
        print(contents)
        DisplayLabel.text = contents as String?
    }
    catch let error as NSError {
        print("Ooops! let path = (NSTemp... did not work: \(error)")
    }

// Another variation with same result:

//具有相同结果的另一个变体:

let file: FileHandle? = FileHandle(forReadingAtPath: "DataFile.plist")

    if file != nil {
        // Read all the data
        let data = file?.readDataToEndOfFile()

        // Close the file
        file?.closeFile()

        // Convert our data to string
        let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print(str!)
        DisplayLabel.text = str as String?
    }
    else {
        print("Ooops! Something went wrong!")
    }

// A version where the final line throws a (syntax -> Edit -> Fatal) error I have been unable to solve:

//一个版本,其中最后一行抛出(语法 - >编辑 - >致命)错误我无法解决:

var dictClients = [String:String]()
    var arrayClients = NSMutableArray()


    let path = Bundle.main.path(forResource: "data", ofType: "rtf")

    let filemgr = FileManager.default

    if filemgr.fileExists(atPath: path!) {
        do {
            let fullText = try String(contentsOfFile: path!, encoding: String.Encoding.utf8)

            let readings = fullText.components(separatedBy: "\n") as [String]

            for i in 1..<readings.count {
                let clientData = readings[i].components(separatedBy: "\t")

                dictClients["FirstName"] = "\(clientData)"

                arrayClients.add(dictClients)
            }
        } catch {
            print("error: \(error)")
        }
    }

    let client = arrayClients[0]
    //DisplayLabel.text = client.
    //DisplayLabel.text = "\(client.ob("FirstName")!) \(client.objectForKey("LastName")!)"

// -Edit - I was able to fix the Syntax error with the below, but got a logic error instead

// -Edit - 我能够用下面的方法修复语法错误,但是却出现了逻辑错误

DisplayLabel.text = "\((client as AnyObject).object(forKey:"FirstName")!) \((client as AnyObject).object(forKey:"LastName")!)"

-- Edit New error --

- 编辑新错误 -

"fatal error: unexpectedly found nil while unwrapping an Optional value"

“致命错误:在展开Optional值时意外发现nil”

I Hope this has somehow been clear, and I appreciate any help in resolving the problem. I have been working on this application since Thursday, and this particular issue since Sunday, with very little sleep or rest, even more computer is struggling to keep running under the strain and my focus is not as strong and I may not be as coherent as I think, so forgive any obvious mistakes I have made or poor communication I may be using.

我希望这在某种程度上是清楚的,我感谢任何帮助解决问题。自星期四以来,我一直在研究这个应用程序,这个特殊的问题从星期日开始,只有很少的睡眠或休息,甚至更多的计算机都在努力保持在紧张的情况下运行,我的重点不是那么强大,我可能不像我想,原谅我所犯的任何明显错误或我可能正在使用的沟通不畅。

Thanks in advance

提前致谢

1 个解决方案

#1


10  

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

主要问题是您无法将富文本(RTF)格式的文本加载到String中。与RTF等效的Cocoa是NSAttributedString。

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

将RTF加载为Data,创建NSAttributedString并获取带有字符串属性的纯文本。

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.

但是对于那种数据结构,RTF是不合适的。更好地使用JSON或属性列表。

#1


10  

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

主要问题是您无法将富文本(RTF)格式的文本加载到String中。与RTF等效的Cocoa是NSAttributedString。

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

将RTF加载为Data,创建NSAttributedString并获取带有字符串属性的纯文本。

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.

但是对于那种数据结构,RTF是不合适的。更好地使用JSON或属性列表。