Reputation: 205
I have created a statistics controller for administrators to export back-end information from a database. The controller has several fields with UIPickers to filter data and a button to send a request to the server, where the API (written in C#) takes care of the export.
The data is currently being exported to a CSV and added back to my controller. The problem is that the attached file contains one extra line break after every line of data. The CSV looks perfect on the Windows machine, though.
If this a Windows / Unix problem where line breaks are handled differently, what can I do to fix this? I want all those extra lines to be gone before the user actually opens the file as a spreadsheet.
On my windows machine
Created by: ""
Created on: ""
Name,Date,Score
Jack Sparrow,2017-07-03-14:48:58,80
Jack Sparrow,2017-07-03-14:49:33,100
On my Mac and iPhone
Created by: ""
Created on: ""
Name,Date,Score
Jack Sparrow,2017-07-03-14:48:58,80
Jack Sparrow,2017-07-03-14:49:33,100
Upvotes: 1
Views: 707
Reputation: 2096
If you want to fix this quick on Mac/iOS client and you don't care about performance that much you could just reconstruct the file by deleting extra new lines. The next approach should work fine and relatively fast if you don't have files with a lot of lines (>500 as a wild guess).
Read file into string:
let fileStr = String.init(contentsOf: yourFileURL)
Get line components:
let comps = fileStr.components(separatedBy: CharacterSet.newlines)
components:separatedBy
will give you empty strings for new lines. Filter out empty strings (in this example all of them, but you can do whatever you need):
let fiteredComps = comps.filter { !$0.isEmpty }
Recompose you string with the necessary new line characters:
var recomposedString = ""
for str in filteredComps {
recomposedString += str
recomposedString += "\n" // or whatever character you need
}
Or check out much shorter answer of the4kman :)
Upvotes: 2
Reputation: 58129
If you want to remove the empty lines alltogether, you can use a simple string replacement function.
let array = string.enumerateLines { line, _ in linesArray.append(line) }
let result = array.filter { !$0.isEmpty }.joined(separator: "\n")
Upvotes: 2
Reputation: 205
I think we found the problem. In Windows a line break is equal to \r\n
, but I needed \n
to make it work on Linux/Unix devices.
Upvotes: 0