swift - 在应用重新启动时保留简单的文本文件

标签 swift

我正在尝试使用以下内容来持久化一个简单的文件:

        if let documents = directories.first {
            if let urlDocuments = URL(string: documents) {

                let urlText = urlDocuments.appendingPathComponent("file.txt")
                print(urlText)
                do {
                    try text.write(to: urlText, atomically: false, encoding: .utf8)
                    print(text)
                }
                catch {}
                true)

            }
        }

但无论我选择什么目录,它都会将其保存在类似的地方

/Users/jaredearl/Library/Developer/CoreSimulator/Devices/6D477D99-7741-472D-8D16-4AE6771AF92E/data/Containers/Data/Appli ... file.txt

那个标签在重新启动和我使用类似的东西时会发生变化:

let documents = "/Users/jaredearl/Desktop/"
        if let urlDocuments = URL(string: documents) {

            let urlText = urlDocuments.appendingPathComponent("file.txt")
            print(urlText)
            do {
                try text.write(to: urlText, atomically: false, encoding: .utf8)
                print(text)
            }
            catch {/* error handling here */}

        }

然后,当我尝试读取文件时,我得到:NSURLConnection 已完成,但出现错误 - 代码 -1002

我怎样才能让它在重启后持续存在?

最佳答案

在 swift 3.0 中

你可以使用相同的函数来读/写文件

func storeSyncLog(txtStor:String) {
    let fileName = "a.txt"        
    let dir = try? FileManager.default.url(for: .documentDirectory,in: .userDomainMask, appropriateFor: nil, create: true)
    //If the directory was found, we write a file to it and read it back
    if let fileURL = dir?.appendingPathComponent(fileName).appendingPathExtension("txt") {
        var inString = ""
        do {
            inString = try String(contentsOf: fileURL)
        } catch {
            print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
        }

        //Write something in file

        let outString = inString + "Date:\(Date()) yd : \(txtStor)\n\n"
        do {
            try outString.write(to: fileURL, atomically: true, encoding: .utf8)
        } catch {
            print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
        }
    }
}

希望对你有帮助

关于swift - 在应用重新启动时保留简单的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48920934/

相关文章:

ios - 将录制的视频保存到照片库 - 无法将类型 'URL' 的值转换为预期的参数类型 'String'

ios - 在 Swift 中调用 REST API

Swift 和 Firebase 查询数据库

Set<Self> 类型的 Swift 协议(protocol)属性

ios - 查看 subview 不可见

swift - 如何在不加载完整缓冲区的情况下启动 AVAudioPlayer?

ios - 登录详细信息未保存在 Xcode 9.4 的 UIWebView 中?

swift - 静态成员 '<top/center/bottom>' 不能用于 'Alignment' 类型的实例

linux - 如何在 Linux 或 OS X 上为 Swift 包生成代码覆盖率?

swift - RealityKit – 在 3d 空间中的两点之间创建线