【问题标题】:How to append a new line to text file in Swift [duplicate]如何在 Swift 中向文本文件添加新行 [重复]
【发布时间】:2018-09-16 13:43:55
【问题描述】:

我正在开发应用程序,当我触摸 iPhone 上的按钮时,我需要添加一个新行。 除了每次它覆盖我所写的内容时,我都这样做了。

每次按保存按钮时如何添加新行。

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var myAge: UITextField!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    // get the documents folder url
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func writeNow(sender: UIButton) {
    let documentDirectoryURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)

    let fileDestinationUrl = documentDirectoryURL.URLByAppendingPathComponent("fileForIphoneAbdulla.txt")

    var text = myAge.text

    do {
        try text!.writeToURL(fileDestinationUrl, atomically: true, encoding: NSUTF8StringEncoding)
        print("file is saved succefully")

        do {
            let mytext = try String(contentsOfURL: fileDestinationUrl, encoding: NSUTF8StringEncoding)
            print(mytext)   // "some text\n"
        } catch let error as NSError {
            print("error loading from url \(fileDestinationUrl)")
            print(error.localizedDescription)
        }
    } catch let error as NSError {
        print("error writing to url \(fileDestinationUrl)")
        print(error.localizedDescription)
    }
}
}

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    高级文件方法用于写入整个文件。

    要追加,您可以使用 NSFileHandle。它有像 seekToEndOfFile 这样的方法将文件指针移动到末尾,然后 writeData 将数据添加到文件末尾。

    顺便说一句,您的示例代码在 Swift 中,但您使用的是 jquery 标记。我假设您正在 Swift 中寻求帮助?

    【讨论】:

    • 我真的很努力地添加并在网上搜索解决方案。你能给我提示一下代码怎么做吗?
    猜你喜欢
    • 2018-07-24
    • 1970-01-01
    • 2020-01-01
    • 2013-02-15
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多