Almazini
Almazini

Reputation: 1873

Save an array to file in Swift

I am building an application which will:

  1. Check internet connection;
  2. Receive JSON file from server and store data in file if server is reachable;
  3. Read from file if connection to server is down.

Right now I managed to implement connection checking, receiving JSON, putting data to array.

Received JSON looks like this:

enter image description here

Then I am using the following peace of code to create an array of dictionaries to store JSON data. Array of dictionaries was chosen to be able to filter it and then using values' keys to reach values.

var rates = [ExchangeRates]()  //instance of class Rate
var bnkDct  =  ["bank": "", "currency": "","buyrate": "", "sellrate": ""] //template
var indx : Int = 0 //index for iteration

            for rate in jsonData{
                let rate = ExchangeRates(data: rate as! NSDictionary)

                rates.append(rate)

                    bnkDct["bank"] = rates[indx].bank
                    bnkDct["buyrate"] = rates[indx].buyRate
                    bnkDct["sellrate"] = rates[indx].sellRate
                    bnkDct["currency"] = rates[indx].currency

                self.bankDict.append(bnkDct)
                indx += 1
            }

After this I have an array which looks like:

enter image description here

Now I would like to save this array to a file and obviously to be able to read it.

I was trying to write data using something like this:

        let filePath = NSTemporaryDirectory() + "MyData.dat"

        self.bankDict.writeToFile(filePath, automatically: true)

But it gives me an error : "[(Dictionary)] doesn't have writeToFile member".

Also I can't cast it as NSDictionary to use the same writeToFile method.

Also I was trying to write data using something like this:

        let filePath = NSTemporaryDirectory() + "MyData.dat"

        NSKeyedArchiver.archiveRootObject(self.bankDict, toFile: filePath)

It creates a file with strange encoding:

enter image description here

And when I am trying to read it:

 let newDictionary = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as! [Dictionary <String,AnyObject> ]

I receive the error: "fatal error: unexpectedly found nil while unwrapping an Optional value"

Also debugger shows very "interesting" thing:

enter image description here

newDictionary variable has zillion of values. There were 40 dictionaries in array which was written in file.

Can anybody advice what I am doing wrong here or maybe I am using bad practices doing something here?

Upvotes: 3

Views: 3694

Answers (1)

Duncan C
Duncan C

Reputation: 131501

You can't use the array or dictionary writeToFile methods unless every object in your object graph is a property list object. (A small list of types. Look it up.)

You have a custom class, ExchangeRates, in your array.

Similarly you can't save a file with NSKeyedArchiver unless every object in your object graph conforms to the NSCoding protocol. If you add support for NSCoding to your ExchangeRates class then your second approach will work, but the file contents will not be human-readable.

Upvotes: 5

Related Questions