Storing an array in a file using Swift

In the process of developing an application, I have successfully implemented functionality to:

  1. Check for an internet connection;
  2. Receive a JSON file from the server and store the data in a file if the server is reachable;
  3. Read from the file if the connection to the server is unavailable.

Currently, I have managed to achieve connection checking, receiving JSON data, and storing it in an array.

The received JSON data has the following structure:

https://i.stack.imgur.com/pQSfA.png

Next, I convert this JSON data into an array of dictionaries in order to easily filter and access values based on their keys:

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
}

As a result, I now have an array that looks like this:

https://i.stack.imgur.com/uIx2f.png

My next step is to save this array to a file and be able to read from it. However, when I attempt to write data using the method below, I encounter an error:

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

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

The error message states: "[(Dictionary)] doesn't have a writeToFile member." I also tried casting it as NSDictionary with no success. As an alternative, I attempted to use NSKeyedArchiver for writing data:

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

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

This approach results in a file with unexpected encoding:

https://i.stack.imgur.com/Ur0kU.png

When trying to read this file, I receive an error:

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

The error message reads: "fatal error: unexpectedly found nil while unwrapping an Optional value." Additionally, upon inspection using the debugger, I noticed a large number of values in the newDictionary variable, indicating an issue with decoding the stored data.

I would appreciate any advice or suggestions on what might be incorrect in my approach or if I am utilizing improper practices in handling this task.

Answer №1

It's important to note that in order to use the array or dictionary writeToFile methods, all objects within your object graph must be of property list types. Make sure to check a comprehensive list of supported types before attempting to save.

If you have a custom class like ExchangeRates within your array, saving it using NSKeyedArchiver won't work unless every object in the graph adheres to the NSCoding protocol. Adding NSCoding support to your ExchangeRates class will enable this method, but keep in mind that the resulting file won't be readable to humans.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JSON_ENCODE may attempt to evade double quotes

I have a controller that retrieves data from my database, formats it as valid JSON, but the HTTP response is text/html instead of application/json. This causes issues with getJSON not working properly. Should getJSON work regardless? public function send ...

Organizing a Collection of Likes within an AngularJS Service

I have a like button on my profile page that, when clicked, should add the user's like to an array and store it in the database. Within my profile controller, I have the following code: $scope.likeProfile = UserService.likeProfile(loggedInUser,$stat ...

One try-catch block in C# handling various classes for distinct JSON messages

I have four distinct classes designated for handling different JSON messages. These messages are always received simultaneously and need to be processed together. All of this is done in a single try-catch block, where I use deserialization to locate the a ...

Working with Linq in JSON Serialization

Below is a json string that I have: { 'Sheet1': [{ 'EmployeeNo': '123456', 'EmployeeName': 'Midhun Mathew' }, { 'EmployeeNo': '123457& ...

Can you provide examples of iterating through multiple maps with key-value pairs using ng-repeat in AngularJS?

Within my controller, the data is structured like so: "type": [ { "aMap": {"5.0": 0}, "bMap": {"10.0": 0}, "cMap": {"15.0": 0}, "dMap": {"20.0": 0}, "desc": "CG" }, { "aMap": {"5.0": 0}, ...

Retrieve information from a web service using PHP function

Is there a way to fetch information from this specific web service using PHP? I'm looking for a straightforward PHP function that can display a list of countries. Information from the Web Service { "valid":true, "id":"0 ...

Performing an asynchronous Ajax call from a partial view in an Asp.net MVC application

Is it possible to use Ajax to fetch data from a form located in a partial view, send it to a controller, and receive a response message? Utilizing Ajax $("#submitContactInfo").on("click", function () { if ($('#contact-form').valid() === true) { ...

Send your information to a JSONP endpoint

Can data be posted to JsonP instead of passing it in the querystring as a GET request? I have a large amount of data that needs to be sent to a cross-domain service, and sending it via the querystring is not feasible due to its size. What other alternati ...

What is the best way to showcase an error message returned as a JSON object from a servlet class using JavaScript/Dojo?

One of my clients has requested a file upload feature through dojo.io.iframe in order to pass binary data to a web application on a websphere app server. The servlet class within the web app then makes a rest web service call to an external system, creatin ...

Creating JSON Objects in PHP

How Can I Generate Similar Json Data Using PHP? [ [ "16226281", "11", "Disclosure.1994.720p.BluRay.H264.AAC-RARBG", "finished" ], [ "16226038", "140", "Courage The Cowardly Dog (1999-2002)", "finished" ], [ "16226020", ...

How can I enable browser caching for test.json, which is generated by json.php using Apache's rewrite feature?

How can I configure browser caching for test.json, which is generated by json.php? Unfortunately, the response headers for test.json are set as if it were a .php file and not a .json file. How do I correctly apply .htaccess rules so that the generated tes ...

What could be the reason behind the disruption in this JavaScript associative array?

I'm facing an issue with my associative array, which I have confirmed through console.log to be initially: this.RegionsChecked = {"US":true,"APAC":true,"Canada":true,"France":true,"Germany":true,"India":true,"Japan":true,"LATAM":true,"MEA":true,"UK": ...

How can I establish a connection between my Android app and a PHP server using HTTPUrlConnection to send data in the output stream and ensure that the server receives it in the $_

When using HttpURLConnection to send a JSON query to a PHP server, I encountered issues with the communication not working as expected. Despite having a successful connection and receiving proper error responses from the server side, it seems that the PHP ...

Encountered issue while transferring the result of urllib.urlopen to json.load

Trying to learn Python and utilizing urllib to download tweets, I encountered a recurring error while following a tutorial. Here is the code snippet causing the issue: import urllib import json response = urllib.urlopen("https://twitter.com/search?q=Micro ...

Is there a constraint on JSON data?

Is there a limit to the amount of data that JSON with AJAX can handle in outgoing and returning parameters? I am trying to send and receive a file with 10,000 lines as a string from the server. How can I accomplish this task? Can a single parameter manage ...

Having trouble extracting JSON from the HTTP response?

Currently, I'm struggling to find a solution in order to properly extract and process the JSON data from . While my code has no issues decoding the JSON data retrieved from , it always returns empty or zero values when directed towards the CoinMarketC ...

Utilizing Ajax to make JSON requests using jQuery

I could really use some assistance here. I have a JSON file and I am attempting to retrieve only one image file by specifying its position, like the first one, for example. Is this achievable? I have experimented with various methods but it seems like some ...

Tips for dynamically changing the field name in a JSON object using Spark

Having a JSON log file with a JSON delimiter (/n), I am looking to convert it into Spark struct type. However, the first field name in every JSON varies within my text file. Is there a way to achieve this? val elementSchema = new StructType() .add("n ...

Creating a dynamic model in an AngularJS directive using a JSON object

I am struggling with utilizing a json file that contains objects storing properties for a directive. Despite my attempts, I cannot seem to access the json obj model value within the directive. Does anyone have any insights into what I might be doing incor ...

Update Android: Sending data to server using PUT request

Feeling a bit frustrated here. Encountering an issue with sending all user inputs via a PUT REST request to the server. Here's how the request JSON object appears on the server: { id: "123", text: "My Name is Peter...", age": 15, name ...