简体   繁体   中英

swift - JSON to CoreData

I try to write the data I get with JSON to my CoreData. when the app launches for the first time, I want to get JSON data, then write it to CoreData and display it in TableViewCell.

But I couldnt 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  
    }
}

I've done this in Objective-C, but I don't have Swift code ready to go for you. Nonetheless, I'll post how I did it w/ Objective-C and you can "translate" it to Swift. I'll assume you've got your Core Data stuff configured.

In my AppDelegate , I added a "check" in didFinishLaunchingWithOptions :

[self seedDataCheck];

At the bottom, I created the following method:

- (void)seedDataCheck {
    // Count what's 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's 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 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 somewhere static like a spreadsheet, you may find this site helpful for getting the data in order to dump into a JSON file.

http://shancarter.github.io/mr-data-converter/

In terms of getting the data to show up in a UITableViewCell , you'll probably want to set up a UITableViewController and configure your prototype cell to display data from your managedObjectContext . That's a pretty "well traveled" path, so I will direct you to take a peek at this tutorial:

http://www.raywenderlich.com/85578/first-core-data-app-using-swift

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM