Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to store static data in app

I am new to app development and are learning about creating apps for iOS. I have a few ideas for some apps all of which will be informational apps having little to no dynamic content.

What I am stuck on is the best approach to storing my static data. I don't want to create separate scenes for every page, as that would mess up my storyboard and would be hard to maintain.

I've looked into creating an API that would serve my content. But since my content would change rarely or never, I don't want to have the user to create a network request every time the app launches. I've then looked into using core data or the Realm database, but I find it hard to find any documentation on pre-filling the database with data as aposed to populating "as-we-go". I've also considered a combination of both, but I also want my app to be 100% offline usable.

I am really struggling on finding what to do. Ideally, I want to go with core data and ship the app with the database pre filled.

I should also mention that I am using Swift. I hope you guys can help me.

like image 906
madsobel Avatar asked Oct 17 '25 11:10

madsobel


2 Answers

In simple cases both CoreData and Realm can be o bit overkill. Especially if your data are readonly and fit into memory with no problem I would consider storing them as JSON file bundled into your application.

This can be done in 3 steps:

  1. Add data.json into your project:

    [
      {"name": "John Doe", "age": 31},
      {"name": "Jane Doe", "age": 25}
    ]
    
  2. Define the model:

    struct Person {
        var name: String
        var age: Int
    }
    
  3. Load the data:

    import SwiftyJSON
    
    
    func loadInitialData() -> [Person] {
        let path = NSBundle.mainBundle().pathForResource("data", ofType: "json")!
        let data = NSData(contentsOfFile: path)!
        let json = JSON(data: data)
    
        var persons = [Person]()
        for (_, item) in json {
            let name = item["name"].string!
            let age = item["age"].int!
            persons.append(Person(name: name, age: age))
        }
    
        return persons
    }
    

    Note: SwiftyJSON is used for better JSON handling.

like image 104
Ondrej Sramek Avatar answered Oct 19 '25 01:10

Ondrej Sramek


Ideally I want to go with core data and shipping the app with the database pre filled.

Prefilled version of Core Data?

Prefill information in Core Data at startup.

like image 22
Cadin Avatar answered Oct 19 '25 00:10

Cadin