Search code examples
iosswiftxcoderealmcodable

Using codable on local JSON file with Realm


I'm trying to add locally stored JSON objects to Realm using codable but I'm unsure if I'm doing it correctly.

realm.add(exercise) is not working but I don't know where I've gone wrong. Assistance would be greatly appreciated.

Here is my JSON data:

[{
"id":"1",
"name":"Bench Press",
"muscle": "chest",
"information":"Lie on the bench and lower the bar until it reaches your chest and then lift it back up" },{
"id":"2",
"name":"Bicep Curl",
"muscle": "bicep",
"information":"Curl the dumbbell"}]

Here is my object class:

@objcMembers class StoredExercise: Object, Decodable {
dynamic var id: Int = 0
dynamic var name: String = ""
dynamic var muscle: String = ""
dynamic var information: String = ""

enum CodingKeys: String, CodingKey {
    case id
    case name
    case muscle
    case information
}

required init(from decoder: Decoder) throws {
    
    let container = try decoder.container(keyedBy: CodingKeys.self)
    
    id = try container.decode(Int.self, forKey: .id)
    name = try container.decode(String.self, forKey: .name)
    muscle = try container.decode(String.self, forKey: .muscle)
    information = try container.decode(String.self, forKey: .information)
    
    super.init()
}

override static func primaryKey() -> String? {
    return "id"
}

required override init() {
    super.init()
}

required init(value: Any, schema: RLMSchema) {
    super.init() 
}

required init(realm: RLMRealm, schema: RLMObjectSchema) {
    super.init() 
}

Here is my realm loading code:

func storeModels() {
guard let url = Bundle.main.url(forResource: "exercises", withExtension: "json") else {
    return
}
do {
    let data = try Data(contentsOf: url)
    guard let exercise = try? JSONDecoder().decode(Exercise.self, from: data) else {
        return
    }
    
    let realm = try Realm()
    print(realm.configuration.fileURL?.absoluteString ?? "")
    
    try realm.write {
        realm.add(exercise)
    }
    
} catch {
    
}

Solution

  • It's an array [Exercise].self

    guard let exercise = try? JSONDecoder().decode([Exercise].self, from: data) else {
        return
    }