Search code examples
iosswiftrealmswifty-json

Realm + Object Mapper + SwityJSON


I need help in mapping my object

Realm Model: https://gist.github.com/n1tesh/7d6c6e155285dd6b39c8edba76f6eba5

This is how I'm doing

    // write request result to realm database
    let entries = json["data"]
    realm.beginWrite()
        let entry: ChatGroups = Mapper<ChatGroups>().map(JSONObject: entries)!
        realm.add(entry, update: true)

    do {
        try realm.commitWrite()
    } catch {

    }

JSON Response: https://gist.github.com/n1tesh/bf84cbd930f8c76b340f21723a217ebe

But i'm getting error fatal error: unexpectedly found nil while unwrapping an Optional value

Please help me out with what I'm doing wrong.


Solution

  • Create a class to transform Array to List, because the Realm doesn't accept arrays.

    import ObjectMapper
    import RealmSwift
    
    public class ListTransform<T:RealmSwift.Object> : TransformType where T:Mappable {
        public typealias Object = List<T>
        public typealias JSON = [AnyObject]
    
        let mapper = Mapper<T>()
    
        public init(){}
    
        public func transformFromJSON(_ value: Any?) -> Object? {
            let results = List<T>()
            if let value = value as? [AnyObject] {
                for json in value {
                    if let obj = mapper.map(JSONObject: json) {
                        results.append(obj)
                    }
                }
            }
            return results
        }
    
        public func transformToJSON(_ value: Object?) -> JSON? {
            var results = [AnyObject]()
            if let value = value {
                for obj in value {
                    let json = mapper.toJSON(obj)
                    results.append(json as AnyObject)
                }
            }
            return results
        }
    }
    

    Then in your ChatGroups class you have to call the Transform function to make the transformation, make this change:

    updated_by              <- map["updated_by"]
    members                 <- map["member"]
    

    to this:

    updated_by              <- (map["updated_by"], ListTransform<QuorgUser>())
    members                 <- (map["member"], ListTransform<GroupMember>())