Fast - JSON to CoreData
I am trying to write the data I receive from JSON to my CoreData. when the app is launched for the first time, I want to receive JSON data and then write it to CoreData and display it in a TableViewCell.
But I couldn't find a way to write JSON to CoreData.
import CoreData
class TableViewCell: UITableViewCell {
@IBOutlet weak var authorLabel: UILabel!
var context: NSManagedObjectContext? {
get {
let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
let _context = appDel.managedObjectContext
return _context
}
}
var author:AuthorList? {
didSet{
self.setupAuthor()
}
}
func setupAuthor(){
var error: NSError?
let request = NSFetchRequest(entityName: "AuthorList")
let results = self.context!.executeFetchRequest(request, error: &error) as! [Article]
if let _error = error {
println("\(_error.localizedDescription)")
}
self.authorLabel.text = author!.authorName
}
}
source to share
I did it in Objective-C, but I don't have Swift code ready for you. However, I'll post how I did it w / Objective-C and you can "translate" it to Swift. I assume you have the kernel content configured.
In mine, AppDelegate
I added "check" to didFinishLaunchingWithOptions
:
[self seedDataCheck];
At the bottom, I created the following method:
- (void)seedDataCheck {
// Count what in the managedObjectContext
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"YourEntity"
inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
NSUInteger itemsInManagedObjectContext = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error];
// If nothing there, import JSON
if (itemsInManagedObjectContext == 0) {
NSLog(@"AppDelegate.m seedDataCheck: importSeedData called");
[self importSeedData];
} else {
NSLog(@"AppDelegate.m seedDataCheck: No import required");
}
}
Then I created a separate method to import the seed data:
- (void)importSeedData {
NSError *error = nil;
// Ensure a managedObjectContext is instantiated
if (![self.managedObjectContext save:&error]) {
NSLog(@"Error while saving %@", ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown error");
} else {
NSLog(@"self.managedObjectContext = %@", self.managedObjectContext);
}
// Create dataPath and put items in an NSArray. Nothing is saved, just exists in memory.
NSError *err = nil;
NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"yourJSONData" ofType:@"json"];
NSLog(@"%@",dataPath);
NSArray *yourArrayOfJSONStuff = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
options:kNilOptions
error:&err];
NSLog(@"AppDelegate.m importSeedData: There are %lu items in the array", (unsigned long)stretches.count);
// Take the array of stuff you just created and dump it in the managedObjectContext
[yourArrayOfJSONStuff enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSManagedObject *yourManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"YourManagedObject"
inManagedObjectContext:self.managedObjectContext];
// Link keys from NSArray * yourArrayOfJSONStuff to NSManagedObjects
yourManagedObject.attribute1 = [obj objectForKey:@"yourAttribute"];
yourManagedObject.attribute2 = [obj objectForKey:@"yourAttribute2"];
// blah blah blah
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}];
NSLog(@"AppDelegate.m importSeedData: Data imported");
}
I'm not sure where you're getting your JSON from, but if it's static somewhere like a spreadsheet, you might find this site useful for getting data to dump JSON files.
http://shancarter.github.io/mr-data-converter/
As far as displaying data in UITableViewCell
, you probably want to customize UITableViewController
and customize your prototype cell to display data from yours managedObjectContext
. This is a pretty "well traveled" path, so I'll make you take a look at this tutorial:
http://www.raywenderlich.com/85578/first-core-data-app-using-swift
source to share