Working with Realm and result JSON

Viewed 679

I am new to realm and I am trying to use Realm in my project. Here I am trying to parse JSON and save it using realm. When I am trying to loop through the result array error occurs

'Attempting to modify object outside of a write transaction - call beginwritetransaction on an RLMRealm instance first'

This is the JSON result:

{"data":[{"id":1,"parent_id":0,"name":"JenniferMaenle","title":"Ms","phone":"","address":"Toled, ohio","email":"jlmaenle@aol.com","image":"44381525_2017.jpg","relation_id":5,"created_at":null,"updated_at":"2017-08-10 02:30:05"},{"id":2, "parent_id":1,"name":"Khadeeja","title":"","phone":"","address":"","email":"","image":"Khadeeja_2017-07-17.jpg","relation_id":2,"created_at":null,"updated_at":"2017-07-17 08:3:12"}]}

I am trying to parse JSON and save it in the Realm database. Here is my try:

class Person: Object {

dynamic var name = ""
dynamic var title = ""
dynamic var address = ""

}

override func viewDidLoad() {
    super.viewDidLoad()
    self.add()

}

func add(){

   guard let data = dataFromFile("ServerData") else { return }

    let persons = Person()

    do {

        if let json = try JSONSerialization.jsonObject(with: data) as? [String: AnyObject] {

            if let data = json["data"] as? [[String:AnyObject]]{

                for eachItem in data{
                    persons.name = eachItem["name"] as! String
                    persons.title = eachItem["title"] as! String
                    persons.address = eachItem["address"] as! String

                    try! realm.write {
                        realm.add(persons)
                    }
                }

            }
        }
    } catch {

        print("Error deserializing JSON: \(error)")
    }
}
2 Answers
Related