简体   繁体   English

快速保存多行文本

[英]Saving multiple lines of text in swift

I am attempting to store multiple lines of text in a local text file on an iphone. 我正在尝试在iPhone的本地文本文件中存储多行文本。 I have code which will create a text document, write data to that document and read data from this document. 我有将创建文本文档,将数据写入该文档并从该文档读取数据的代码。

However, if i try and add more text to this document, it will only store the most recent line of text which has been added. 但是,如果我尝试向此文档中添加更多文本,它将仅存储已添加的最新文本行。

The code I have for creating, writing and reading text from this document is as follows: 我从该文档创建,编写和读取文本的代码如下:

//Storing user rewards
    let fileName = "Rewards"
    let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let fileURL = DocumentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")

   //print("File Path: \(fileURL.path)")

    let writeString = rewardLBL.text
   do {
        //writing to the file
        try writeString?.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
    } catch let error as NSError{
        print("failed to write")
        print(error)
    }

    var readString = ""
    do {
        readString = try String(contentsOf: fileURL)
    }catch let error as NSError{
        print("failed to readFile")
        print(error)
    }

    print(readString)

I need this to allow for multiple entries of text to be stored, rather than just the most recent data which was written. 我需要这样做,以允许存储多个文本条目,而不只是存储最近写入的数据。

I suspect that due to the code being inside the 'viewDidLoadi()' method that it is constantly recreating the same document and thus always making a new version which overwrites the old Rewards.txt document. 我怀疑由于代码位于“ viewDidLoadi()”方法内部,因此它会不断重新创建同一文档,从而始终制作一个新版本来覆盖旧的Rewards.txt文档。

Any help is greatly appreciated, thanks. 非常感谢任何帮助,谢谢。

Since you are using write, it will overwrite whatever is written earlier. 由于您正在使用写操作,因此它将覆盖之前写的任何内容。

try writeString?.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8) 尝试writeString?.write(收件人:fileURL,原子性:true,编码:String.Encoding.utf8)

You need to append line of text to your file, which will not overwrite previous written lines. 您需要将文本行添加到文件中,这不会覆盖以前编写的行。 Something like this: 像这样:

writeString.data(using: String.Encoding.utf8)?.write(to: fileURL, options: Data.WritingOptions.withoutOverwriting)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM