Skip to content

Instantly share code, notes, and snippets.

@joshdholtz
Created December 15, 2015 02:54
Show Gist options
  • Save joshdholtz/35d01d5f60eda9c48c47 to your computer and use it in GitHub Desktop.
Save joshdholtz/35d01d5f60eda9c48c47 to your computer and use it in GitHub Desktop.
Import JSON object/array into RestKit
// Imports comment JSON into RestKit
let json: RestKitJSON = ["some_key": "some_value"] // [NSObject: AnyObject]
importObject(json, finished: { (model: YourModel?) -> () in
print("YourModel - \(model)")
})
import Foundation
typealias RestKitJSON = [NSObject: AnyObject]
func importObject<T: NSManagedObject>(object: RestKitJSON?, objectStore: RKManagedObjectStore = RKManagedObjectStore.defaultStore(), finished: (object: T?) -> ()) {
guard let object = object else {
finished(object: nil)
return
}
importObjects([object], objectStore: objectStore, finished: { (objects: [T]?) -> () in
finished(object: objects?.first)
})
}
func importObjects<T: NSManagedObject>(objects: [RestKitJSON]?, objectStore: RKManagedObjectStore = RKManagedObjectStore.defaultStore(), finished: (objects: [T]?) -> ()) {
guard let objects = objects else {
finished(objects: nil)
return
}
// Get mappings for class
var mappings = [NSObject: AnyObject]()
let descriptors = RKObjectManager.sharedManager().responseDescriptors as? [RKResponseDescriptor] ?? []
for descriptor in descriptors {
if let mapping = descriptor.mapping as? RKEntityMapping
where mapping.objectClass === T.self {
mappings[descriptor.keyPath] = mapping
}
}
// Get the mapper
guard let mapper = RKMapperOperation(representation: objects, mappingsDictionary: mappings) else {
finished(objects: nil)
return
}
// Get datasource
let datasource = RKManagedObjectMappingOperationDataSource(
managedObjectContext: objectStore.persistentStoreManagedObjectContext,
cache: objectStore.managedObjectCache
)
mapper.mappingOperationDataSource = datasource
// Create queue for mapping operation to run
let queue = NSOperationQueue()
queue.addOperation(mapper)
queue.waitUntilAllOperationsAreFinished()
// Run and wait for the mapping to run in the context
let context = RKManagedObjectStore.defaultStore().persistentStoreManagedObjectContext
context.performBlock({ () -> Void in
do {
try context.saveToPersistentStore()
let objects = mapper.mappingResult.array() as? [T]
finished(objects: objects)
} catch _ {
finished(objects: nil)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment