2

I am trying to create a simple CVS file in document directory on iPad or temp directory. This code is as follows:

 let fileName = "test.csv"

        _ = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)

I am then trying to modify the file using CSV.swift library from github like this:

let stream = OutputStream(toFileAtPath: "test.csv", append: false)!

        let csv = try! CSVWriter(stream: stream) // Error at this line


        try! csv.write(row: headerarray)
        try! csv.write(row: dataarray)

        csv.stream.close()

For some reason I am getting error saying CSV.CSVError.cannotOpenFile: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-802.0.53/src/swift/stdlib/public/core/ErrorType.swift

It doesn't look like I am creating the .csv file correctly.

Martheli
  • 931
  • 1
  • 16
  • 35

1 Answers1

3

You are throwing away the path to the Temporary Directory in the second line. That is your problem. So instead of adding fileName inside the Temporary Directory, you are trying to add it to the root of your hard disk. I doubt you have permissions for this and therefore fail to create the file. Try building up the full pathname like I do in the first line of the function below.

Here is a function that writes a String to a file in the Temporary Directory using streams.

func streamTextToFile(_ text: String) {
  let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("test.csv")
  guard let stream = OutputStream(toFileAtPath: url.path, append: false) else { return }
  let data = [UInt8](text.utf8)
  stream.open()
  stream.write(data, maxLength: data.count)
  stream.close()
}

Here is some sample output. enter image description here

Price Ringo
  • 3,424
  • 1
  • 19
  • 33