【问题标题】:Swift: Ask user to input the text file name after each stop button is clickedSwift:单击每个停止按钮后要求用户输入文本文件名
【发布时间】:2020-06-10 17:08:28
【问题描述】:

我创建了一个可以收集数据的停止按钮,点击停止按钮后会保存到定义的路径。但是,如果我想在单击停止按钮后继续收集,数据将被添加到原始文本文件中。 (这是有道理的,因为我只知道如何定义一条路径)

我的问题是:是否可以在每次停止后询问用户并输入新的文件名并另存为新的文本文件,这样数据就不会添加到原始文件中?

以下是我所拥有的一个已定义路径并堆叠数据:

    @IBAction func stopbuttonTapped(_ btn: UIButton) {
        do {
            let username:String = user_name.text!
            fpsTimer.invalidate() //turn off the timer
            let capdata = captureData.map{$0.verticesFormatted}.joined(separator:"") //convert capture data to string
            let dir: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! as URL
            let url = dir.appendingPathComponent("testing.txt") //name the file
            try capdata.appendLineToURL(fileURL: url as URL)
            let result = try String(contentsOf: url as URL, encoding: String.Encoding.utf8)
        }
        catch {
            print("Could not write to file")
        }
}

以及我用于字符串和数据的扩展名:

 extension String {
   func appendLineToURL(fileURL: URL) throws {
        try (self).appendToURL(fileURL: fileURL)
    }

    func appendToURL(fileURL: URL) throws {
        let data = self.data(using: String.Encoding.utf8)!
        try data.append(fileURL: fileURL)
    }
    func trim() -> String
      {
       return self.trimmingCharacters(in: CharacterSet.whitespaces)
      }
}
extension Data {
    func append(fileURL: URL) throws {
        if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
            defer {
                fileHandle.closeFile()
            }
            fileHandle.seekToEndOfFile()
            fileHandle.write(self)
        }
        else {
            try write(to: fileURL, options: .atomic)
        }
    }
}

我是否需要设置一个默认文件名(可能是 texting.txt),然后弹出一个用户输入来保存文本文件? (这就是我不太确定如何整合到我已有的东西的地方)。非常感谢您提前提供的时间和建议。

【问题讨论】:

    标签: ios swift iphone xcode


    【解决方案1】:

    您可以生成唯一的名称。

    例如:

    let url = dir.appendingPathComponent("testing-\(Date.timeIntervalSinceReferenceDate).txt")
    

    let url = dir.appendingPathComponent("testing-\(UUID().uuidString).txt")
    

    【讨论】:

    • 感谢您的回复!每次点击后它都会输出一个单独的文件!对于文件名,我得到了我不太明白的时间编号,它的613509736.89就像这样。有可能得到当前时间吗?我试过 Date().timeIntervalSinceNow 仍然给了我一些我不太明白的数字
    • 自参考日期以来的秒数。您可以使用反转它的 Date init 将其转换回日期。您还可以格式化以使其可读:medium.com/@lugearma/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 2021-11-23
    相关资源
    最近更新 更多