I want to use a centralized database and am looking at various options to do so. From my understanding, I have three main options: SQLite, Realm, and CoreData. Are these options fine for a large centralized database for all users.
Additionally, I am trying to import data from JSON and CSV into a Realm database. Does Realm have this functionality?
As for now Realm does not seem to have the import functionality that you need. Check this thread for more information.
Realm does have a great documentation that you can read at Realm and for SQLite there is this framework (there are for sure more out there) and they both support Swift 2.x. You have to check what suits your requests most.
I can also recommend you to read this database thread at reddit.
public String composeJsonFromRealm(){
ArrayList<HashMap<String, String>> wordList;
wordList = new ArrayList<HashMap<String, String>>();
// Build the query looking at all users:
// Execute the query:
RealmResults<User> users = realm.where(User.class).findAll();
if (users.size()>0){
User user = users.first();
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", user.getName());
map.put("email",user.getEmail());
wordList.add(map);
}
Gson gson = new GsonBuilder().create();
return gson.toJson(wordList);
}
I am trying to import data from JSON and CSV into a Realm database. Does Realm have this functionality?
With Realm Cocoa Converter you can import CSV, XLSX, and JSON, and export CSV data. Though, at the moment, it only supports OS X.
As of now, Realm Studio does have the import functionality from CSV.
Open the Realm Studio, File -> Create Realm from -> CSV
Cheers,
Murat
Related
I'm using SwiftyJSON to get a JSON from my web service. What's the easiest way to convert this into a swift object represenation?
I mean maybe a website like http://www.jsonschema2pojo.org/ which does the same for Java.
I so far found generators which work from String or Dictionary but not SwiftyJSON?
Thanks
You can see JSON Master, Here you can generate you code directly from JSON for SwiftyJSON, Codable framework or classical Dictionary. It can also generate struct or class.
Also it has support for Java, Kotlin and C#
You can use json4swift
Online JSON to Swift Models Generator
Our motive is simple, in this age of technology; convenience and automation, working with JSON for Swift shouldn't be complicated anymore. Without dependency on other tools and framework, this free online utility maps your web service responses to appropriate models. It makes working with JSON easier and manageable.
Free Utility
This online free utility generates a Swift 2.0 and Swift 4.0 compatible models which can be simply dragged & used in your project.
Map Response
Simply map your web service response with your models with a single line.
Dictionary Representation
The objects can be referred to as a dictionary anytime should you need them with the current state and same key-value pairs.
Let's say for example you have a Student Model and you want to map the JSON Object to Student Object. You can try like this:
struct Student {
let id: Int!
let name: String!
init(param: JSON) {
id = param["id"].intValue
name = param["name"].stringValue
}
/* JSON Response
{
"id": 168,
"name": "KoingDev"
}
*/
}
Hope it is useful! :)
I am developing an iOS app using Swift (still new to swift).
I have a databank saved as a csv file and that is primarily the core of the app. The databank contains a table divided into a list of all countries (rows) each with many attributes/descriptors (the columns). Really there is no relationship between the countries.
What I would like to do is to be able to display this information for the (selected) country in my app. As well as do other things like search/filtering/sorting based on the attribute/property chosen.
The databank might be updated in the future with the release of app updates but other than that I think I want it to be read once from the csv file and then the app uses that data.
Am I right in thinking that the best way to implement this is by using Core Data with ONE entity (country) with the different attributes? So then all I have to do is read the csv file once and persistent store all the data and use it from there.
Or is Core Data not the best implementation? Shall I just create a class Country with the many attributes and use that? But then that means the app will have to read the csv every time it opens and save the data to arrays etc if I wanted to filter or sort?
So I guess in summary my questions are:
1. Use Core Data or not? If not then what do you think the best implementation is?
2. If using Core Data, am I just creating ONE entity (so no relationships etc).
What would see this as is that you would want to load this into your database of choice; Thus CoreData or SQLite or even Realm would work.
In case you don't have the data available for any of them yet and you want to load them in using swift this is a parser that I wrote for a similar situation where CSV is my raw datasource that I need to parse:
if let listFile = try? String(contentsOfFile: path) {
let lines = listFile.components(separatedBy: "\n")
// NOTE: There is also a CSV format that uses ',' as a separator
// So verify if yours uses ';' or ','
let rows: [[String: String]] = lines.flatMap() {
(item) -> [String: String]? in
let components = item.components(separatedBy: ";")
if components.count != 3 {
return nil
}
// Modify this part to parse the X amount of columns
// you have in your countries.csv
let dict = [
"identity": components[0],
"description": components[1].lowercased(),
"points": components[2]
]
return dict
}
}
}
Then after you have the data in an [[String: String]] format you could parse that row by row and insert them into the database you chose to use.
I believe in Swift4 it should be possible to use the new Codable protocols in order to achieve a result that would look a lot cleaner; but I have not written an Encoder/Decoder for CSV files ( yet ) that would allow you to do this. If there is one available I'll post it here.
There is also a CSV parser available on github here:
SwiftCSV
I have never used it, but who knows; might be helpful to you.
I don't have access to an OData provider just a simple REST api with json and I need to store the data locally (on the mobile device websql) in different tables reflecting the backend model. Following the Edmunds example I have got the entity and the relationships working from the REST api. How can I make it work the same way from the data stored locally. I would like to fetch the data from the local DB and recreate my entities, any advice would be appreciated thanks.
After you have queried the data thru the REST api, just export the EntityManager to local storage. Something like this
var changesExport = myEntityManager.exportEntities();
ok(window.localStorage, "this browser supports local storage");
var stashName = "arbitrary name for storage area"";
window.localStorage.setItem(stashName, changesExport);
This data can later be reimported into any existing EntityManager, and then queried locally by simply reimporting the data.
importedData = window.localStorage.getItem(stashName);
anotherEntityManager.importEntities(importedData);
I have an app that has some data ( static ) that needs to be shipped out with the app. The client gave me this data in Excel(over 300 rows), now I created a model for this in coredata, I was wondering is there a way or a tutorial that shows how can I make an import from excel into my model ? or if someone thinks of a better approach to incorporate this data( SQLLite maybe)?
Thanks
There is a way to import CSV data into sqlite3 at the command line; however, it is recommended that you not do this, since Core Data creates sqlite fields that would need to be dealt with.
If you start with CSV, you could look at doing something like this:
http://macresearch.org/cocoa-scientists-part-xxvi-parsing-csv-data
perhaps with modification to work with your dataset.
To import the data into your application and store it in Core Data I would export the Excel Data to a CSV file. That filetype is easy to parse. I don't know about any libraries that parse Excel files directly. Your code does than look like this.
NSString *fileContent = [NSString stringWithContentsOfFile:#"path/to/file.csv" usedEncoding:&enc error:nil];
NSArray *lines = [fileContent componentsSeparatedByString:#"\n"];
for (NSString *currentLine in lines) {
// Handle this line and store in model
NSArray *fields = [currentLine componentsSeperatedByString:#";"]; // Or other delimiter
// From the excel file you know which column is which property in the model.
// Populate the entity appropriately and store it
}
The above code is without guarantee. I didn't test the code.
I'm looking for the best method for importing csv or excel file to SQL Server 2005 using .net MVC.
Thank you.
There's a really good library called FileHelpers which is a) 100% free, b) fully in C#, and it can easily import any kind of text-based file - comma-separated, tab-separated, fixed width and so on.
You should have no trouble using this to load your CSV file into in-memory objects and storing those in SQL Server using ADO.NET.
In FileHelpers, you first need to have a class that describes your data, e.g. a "Customer" class (or whatever it is you're importing).
Then, you can import a file using code something like this:
FileHelperEngine<Customer> engine = new FileHelperEngine<Customer>();
Customer[] dataLoaded = engine.ReadFile(fileName);
Once you have your array of customers, you can either just iterate through that and save the data (typically inside a transaction) with e.g. a stored procedure or a ad-hoc SQL query:
using(TransactionScope ts = new TransactionScope())
{
foreach(Customer c in dataLoadad)
{
SaveCustomer(c);
}
ts.Complete();
}
or you could convert the customer array to a DataTable and use SqlBulkCopy to bulk insert that into your SQL Server database - there are lots of options!
UPDATE:
Do you have a [DelimitedRecord] or another of those attributes on your BlackListDevice class?
Fixed this by adding a seperate class for file uploads, works like a charm using the FileHelper.