3

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?

11
  • I think you should have a look into Core Data. Here is a good link to start: raywenderlich.com/85578/first-core-data-app-using-swift Commented Sep 15, 2015 at 10:41
  • Remove the typecast as! [Dictionary <String,AnyObject> ] and see what the value is. Commented Sep 15, 2015 at 10:43
  • My guess is that you're loosing the saved file between app launches because the NSTemporaryDirectory path changes everytime the app launches. Solution would be to save it to a permanent location. As for newDictionary and 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. Commented Sep 15, 2015 at 10:43
  • @EricD. Thanks for reply, but it seems that it finds file well. I am using function: func getFileURL(fileName: String) -> NSURL { let manager = NSFileManager.defaultManager() let dirURL = manager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false, error: nil) return dirURL!.URLByAppendingPathComponent(fileName) } let filePath = getFileURL("MyData.dat").path! and I tried to compare file paths they match. Commented Sep 15, 2015 at 10:51
  • @Adam when I remove typecast it shows me warning. If I ran application it uses AnyObject? type and value is nil Commented Sep 15, 2015 at 10:54

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain how should I use NSCoding?
Perfect link for an introduction to NSCoding. Thank you for adding that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.