I'm using Objective-C the last years. Now I'm trying the Xcode 6 beta 4 with swift.
I want to import a .csv form my webserver to an array. My old code in Objective-C was:
NSString *stringURL = @"https:// [URL] /versionen/versionen.csv";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSString *csvResponseString = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
NSArray *MZVersionDatenZeilen = [csvResponseString componentsSeparatedByString:@"\n"];
NSEnumerator *MZVersionEnumerator = [MZVersionDatenZeilen objectEnumerator];
NSMutableArray *MZVersionDatenArray = [NSMutableArray arrayWithCapacity:[MZVersionDatenZeilen count]];
NSString *MZVersionZeile;
while (MZVersionZeile = [MZVersionEnumerator nextObject])
{
[MZVersionDatenArray addObject:[MZVersionZeile componentsSeparatedByString:@";"]];
}
}
How could I do this in Swift? Is there a best practices - recommendation?
Every answer requires you to install/download a 3rd party utility, but that may not be optimal if the file you're working with is extremely simple or you work at an company that restricts 3rd party code.
So I figured I would just post incredibly basic, routine CSV file handling code that people can use as a base and modify as needed for simple CSV handling.
do {
let file = try String(contentsOf: fileUrl)
let rows = file.components(separatedBy: .newlines)
for row in rows {
let fields = row.replacingOccurrences(of: "\"", with: "").components(separatedBy: ",")
print(fields)
}
} catch {
print(error)
}
This will handle any CSV files that you know won't have quotes and commas as part of the content of a field, which in my case are most CSV files. Anything more complex than this, I recommend using one of the libraries posted in the other answers.
I just hope this saves someone a bit of typing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With