创建多行文本并将其写入文本文件(CSV)?

时间:2019-06-06 14:34:54

标签: swift csv

我正在尝试为用户创建一种登录方式,并将用户名和密码存储在文本文件中。这是针对学校项目的,因此它没有安全地存储,我想我也没有时间设置/学习如何序列化数据。 我遇到的主要问题是尝试将数据编写为CSV格式,以便以后根据从文本文件接收到的数据将用户的得分分为一个数组。

我尝试了另一种写入文本文件的方法:
writeString.data(using: String.Encoding.utf8)?.write(to: fileURL, options: Data.WritingOptions.withoutOverwriting)但这似乎对我不起作用

struct UserAccount: Codable {
        var username: String
        var password: String
        var scores: [Int]
    }

var user = UserAccount(username: "", password: "", scores: [0])

func writeTextFile(_ user: UserAccount) {
    //Creating text file to read and write user's data (username, password, and score values)
    let fileName = "UserDataQuizApp"
    let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

    do {
        let fileManager = FileManager.default

        if fileManager.fileExists(atPath: "UserDataQuizApp") {
            try fileManager.removeItem(atPath: fileName)
        }
    } catch {print("error when deleting \(fileName)") }

    // If the directory was found, we write a file to it and read it back
    if let fileURL = dir?.appendingPathComponent(fileName).appendingPathExtension("txt") {
        print("The path is: \(fileURL)")

        do {
            try user.username.write(to: fileURL, atomically: false, encoding: .utf8)
            try ",".write(to: fileURL, atomically: false, encoding: .utf8)
            try user.password.write(to: fileURL, atomically: false, encoding: .utf8)
            for i in 0 ... user.scores.count {
                try ",".write(to: fileURL, atomically: true, encoding: .utf8)
                try String(user.scores[i]).write(to: fileURL, atomically: true, encoding: .utf8)
            }
        } catch {
            print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
        }
    }
}

将数组写入文本文件现在根本不起作用,因为它说索引超出范围,但是当我注释掉它并尝试仅写入用户名和密码时,只有密码在我检查文件时。我期待用户名,逗号和密码输入

1 个答案:

答案 0 :(得分:0)

崩溃原因在for i in 0 ... user.scores.count行中,应该为for i in 0 ..< user.scores.countfor score in user.scores

并且您正在尝试将每个文本写入文件。 这意味着只有最后一个write(to:..才有效。所写的所有内容都会被覆盖。

要解决此问题,请创建一个包含所有信息的字符串,然后将其写入文件。 例如,写功能应该像:

func writeTextFile(_ user: UserAccount) {
        //Creating text file to read and write user's data (username, password, and score values)
        let fileName = "UserDataQuizApp"
        let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

        do {
            let fileManager = FileManager.default

            if fileManager.fileExists(atPath: "UserDataQuizApp") {
                try fileManager.removeItem(atPath: fileName)
            }
        } catch {print("error when deleting \(fileName)") }

        // If the directory was found, we write a file to it and read it back
        if let fileURL = dir?.appendingPathComponent(fileName).appendingPathExtension("txt") {
            print("The path is: \(fileURL)")

            do {
                var contents = [user.username, user.password]
                contents.append(contentsOf: user.scores.map { "\($0)"})
                let string = contents.joined(separator: ",")
                print("contents \(string)")
                try string.write(to: fileURL, atomically: false, encoding: .utf8)
            } catch {
                print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
            }
        }
    }