I am building an application which will:
- Check internet connection;
- Receive JSON file from server and store data in file if server is reachable;
- 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:
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:
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:
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:
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?




as! [Dictionary <String,AnyObject> ]and see what the value is.NSTemporaryDirectorypath changes everytime the app launches. Solution would be to save it to a permanent location. As fornewDictionaryand its zillion items, it's just the debugger freaking out because it can't find the actual variable content if stopped after the variable declaration but before it is filled. I bet the variable is actually empty.