Write NSData in NSHomeDirectory

96 views Asked by At

I am stuck with a problem

I create a JSON data from CoreData Entity.

// name : String
// index : String
// image : NSData
var asJson : [String:AnyObject]{
    return ["name" : name, "index" : index , "image" : "\(image)"]
}

Total Records I want to save it in a file.

let fetch = NSFetchRequest(entityName: kCreditCardCompanies)
    let allCredits = ManagedDocument.sharedInstance.managedObjectContext.executeFetchRequest(fetch, error: nil) as! [CreditCardCompanies]

    for cards in allCredits{


      var jsonCard = ["cards" : cards.asJson]

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
           var jsonData = NSJSONSerialization.dataWithJSONObject(jsonCard, options:
                NSJSONWritingOptions.PrettyPrinted, error: nil)!
            var path = NSHomeDirectory().stringByAppendingPathComponent("Documents")
            var directory = path.stringByAppendingPathComponent("creditCard.json")
            jsonData.writeToFile(directory, atomically: true)

            println("\(jsonData)")
        })

    }

in " jsonData " all record exist , but in the file " creditCard.json " only 1 record is saved , not all .

Where is my fault ?

1

There are 1 answers

0
Good Doug On

Each pass through, you are saving one instance of the card data into the "creditCard.json" file. If you want to write out all of the cards into a file that looks like:

{
"cards": [
    {"name": "foo", "index":12, "image": "<hex data>"},
    {"name": "bar", "index":13, "image": "<hex data>"}
]
}

Then you will want to gather all the cards into an array before making them into a json object, take out your for loop and map the allCredits to the json representation

replace this:

for cards in allCredits{
    var jsonCard = ["cards" : cards.asJson]

with:

let jsonCard = ["cards": allCredits.map {$0.asJson}]

That line will create a dictionary where the key is "cards" and the value is an array of the items in allCredits as json.