你如何从 Swift 3 (XCode 8) 中的文本文件中读取数据 [英] How do you read data from a text file in Swift 3 (XCode 8)

查看:55
本文介绍了你如何从 Swift 3 (XCode 8) 中的文本文件中读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

first I would like to start with my current situation:

1) 现状:

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

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.

我一直试图从该文件中读取任何数据,并在标签上显示该数据.

I have been trying to read ANY data from this file, and show that data on a 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.

三天来,我搜索了各种说明和教程,了解如何执行通常是相当简单的功能.我已经使用 Objective-C 做到了,但我是 Swift 的新手,不幸的是,我不得不使用它来进行这个评估,但我被卡住了.

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.

2) 障碍:

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

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:

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 "无法打开文件data.rtf",因为没有这样的文件.没有这样的文件或目录"

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

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

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

3) 代码:

在这一点上,我对一个有效的代码更感兴趣,而不是修复我的无效的代码,因为我在尝试解决这个问题(以及其他 XCode 更新相关问题)的过程中变得如此痛苦,以至于它即使我绕过这个障碍,也几乎不适合目的,但如果有帮助,我将提供一些"我所做的不同尝试

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

//找不到文件的代码":

// 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 - 我能够用下面的代码修复语法错误,但出现了逻辑错误

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

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

-- 编辑新错误 --

-- Edit New error --

致命错误:解包可选值时意外发现 nil"

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

我希望这在某种程度上是清楚的,我感谢任何帮助解决问题.我从星期四开始研究这个应用程序,从星期天开始这个特殊的问题,很少睡觉或休息,更多的电脑在压力下努力保持运行,我的注意力没有那么强,我可能没有那么连贯我想,请原谅我犯的任何明显错误或我可能使用的沟通不畅.

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.

提前致谢

推荐答案

主要问题是您无法将富文本 (RTF) 格式的文本加载到 String 中.相当于 RTF 的 Cocoa 是 NSAttributedString.

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

将 RTF 加载为 Data,创建一个 NSAttributedString 并使用 string 属性获取纯文本.

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

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

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

这篇关于你如何从 Swift 3 (XCode 8) 中的文本文件中读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆