user10094829
user10094829

Reputation:

Get csv file in realm database with Swift

I have a csv file which looks like this

Tag1,Tag2,Tag3,
some1,some2,some3,
some4,some5,some6,

is there a way to import this file to the realm database programatically?

Like everytime the app starts the new csv file should be imported in the realm database.

The Tag1,Tag2,Tag3, should be the column headers and the some... should be the values

Upvotes: 0

Views: 1782

Answers (2)

David Pasztor
David Pasztor

Reputation: 54706

There is no out-of-the box solution at the moment for programatically importing contents of a csv file to an existing realm file.

You can use Realm Studio to create a new realm file from a csv file. Realm Cocoa Converter can also be used to generate a new realm file from one or more csv files, however, to be able to import files into an already existing realm file, you'd need to modify the converter. Bear in mind that Realm Cocoa Converter only support macOS, it cannot be used in an iOS project.

Or you can write your own code for converting a csv file to Realm Objects. Parsing a CSV file is quite easy, validating it to make sure it can be converted to Realm objects is a bit more complicated. However, from JSON/plist you could automatically parse Realm objects using Codable.

Upvotes: 1

Kentaro Okuda
Kentaro Okuda

Reputation: 1582

My macOS app imports contents of a tsv file to an existing realm file . Here is my function to read a file.

func readFileFrom(_ fileURL: URL) -> [[String]]? {
  do {
    let content = try String(contentsOf: fileURL, encoding: .utf8)
    let data: [[String]] = content.components(separatedBy: "\r\n").map { $0.components(separatedBy: "\t") }
    return data
  } catch {
    //
  }
  return nil
}

I then pass the returned data to my Realm manager class that generates and adds new objects.

guard let data = readFileFrom(url) else { return }
RealmManager.write(data: data)

For csv files, you can change components(separatedBy: "\t") to components(separatedBy: ",").

Upvotes: 2

Related Questions