Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: saving objects into CoreData directly from JSON api rest

I'd need some suggestions about iOS store developing: I need to import data from Rest Api into CoreData of my application in the fastest way possible.

I would like to use Alamofire + ObjectMapper or directly AlamofireObjectMapper to map JSON results into my custom objects model and then save them into CoreData.

I tried to use AlamofireObjectMapper but I don't manage to set Mappable custom NSManagedObject I use to save record into CoreData DB, as explained here

https://github.com/tristanhimmelman/AlamofireObjectMapper

Until now, I used this guide http://code.tutsplus.com/tutorials/core-data-and-swift-subclassing-nsmanagedobject--cms-25116

to create two class

MyCustomObjectClass.swift

MyCustomObjectClass+CoreDataProperties.swift

but, there is a way to set MyCustomObjectClass mappable so that with a simple AlamofireObjectMapper api request I get JSON, create objects and store them directly?

Other possible solutions?

Thank you for help

like image 769
dayroma Avatar asked Oct 31 '25 00:10

dayroma


1 Answers

To parse json to NSManagedObject subclasses, I recommend Groot. It requires a little configuration, but it works great.

I also created a cocoapod called AlamofireCoreData, that wraps Groot into a Alamofire serializer, I think you can use to do exactly what you ask for:

// User is a `NSManagedObject` subclass
Alamofire.request(url)
    .responseInsert(context: context, type: User.self) { response in
        switch response.result {
        case let .success(user):
            // The user object is already inserted in your context!
        case .failure:
            // handle error
        }
}

Hope it can help you.

like image 148
manueGE Avatar answered Nov 01 '25 12:11

manueGE