Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store JSON response in Core Data?

I have a Core Data object.

I was curious, as a relatively inexperienced iPhone developer, whether anyone could recommend an approach, and a suitable JSON implementation for the iPhone, which would allow me to store JSON responses as Core Data objects.

I'm getting 5 records (dictionaries) from JSON response. I need to store them in Core Data, and retrieve them when ever necessary .

I have searched, unsuccessfully, for a tutorial/code sample on this point so any assistance would be gratefully received.

like image 924
user3420042 Avatar asked Mar 28 '14 05:03

user3420042


2 Answers

You can check here also, They have explained from beginning, you can follow and will get it

http://www.appcoda.com/fetch-parse-json-ios-programming-tutorial/

http://maniacdev.com/2013/04/library-for-integrating-web-services-turning-json-data-into-core-data-backed-native-objects

like image 121
ChenSmile Avatar answered Oct 31 '22 18:10

ChenSmile


Set your Core Data property to transformable. Then use this extension:

extension NSObject {
    static func storeJSON(dataToStore: [String: AnyObject], completion: (data: NSData?) -> Void) {
        do {
            let data = try NSJSONSerialization.dataWithJSONObject(dataToStore, options: [])
            completion(data: data)
        } catch let error as NSError {
            print("NSJSONSerialization Error: \(error)")
            completion(data: nil)
        }
    }

    func retrieveJSON(completion: (json: JSON) -> Void) {
        if let data = self as? NSData {
            do {
                let nsJSON = try NSJSONSerialization.JSONObjectWithData(data, options: [])
                completion(json: JSON(nsJSON))
            } catch let error as NSError {
                print("NSJSONSerialization Error: \(error)")
                completion(json: nil)
            }
        }
    }
}

If you don't use SwiftJSON then just use:

extension NSObject {
    static func storeJSON(dataToStore: [String: AnyObject], completion: (data: NSData?) -> Void) {
        do {
            let data = try NSJSONSerialization.dataWithJSONObject(dataToStore, options: [])
            completion(data: data)
        } catch let error as NSError {
            print("NSJSONSerialization Error: \(error)")
            completion(data: nil)
        }
    }

    func retrieveJSON(completion: (json: AnyObject?) -> Void) {
        if let data = self as? NSData {
            do {
                let nsJSON = try NSJSONSerialization.JSONObjectWithData(data, options: [])
                completion(json: nsJSON)
            } catch let error as NSError {
                print("NSJSONSerialization Error: \(error)")
                completion(json: nil)
            }
        }
    }
}

Example use with user.jsonTest as a transformable in core data:

func testThis() {
    makeSaveData() {
        self.user.jsonTest!.retrieveJSON() {
            json in
            print("json: \(json)")
        }
    }
}

func makeSaveData(completion: () -> Void) {
    var solarResourceDic: [String: String] = [:]
    var srDics: [[String: String]!] = []

    for i in 0..<5 {
        solarResourceDic = [:]
        solarResourceDic["system_capacity"] = "\(i)"
        solarResourceDic["azimuth"] = "\(i + 1)"
        solarResourceDic["tilt"] = "\(i + 2)"
        solarResourceDic["array_type"] = "\(i + 3)"
        solarResourceDic["module_type"] = "\(i + 4)"
        solarResourceDic["losses"] = "\(i + 5)"
        srDics.append(solarResourceDic)
    }
    let dic = ["Solar Resource": srDics]

    NSObject.storeJSON(dic) {
        data in
        if data != nil {
            self.user.jsonTest = data
            appDelegate.coreData.saveContext()
            completion()
        } else {
            print("Error storing data")
        }
    }
}
like image 43
Sethmr Avatar answered Oct 31 '22 18:10

Sethmr