As I’ve mentioned in my previous posts over the past couple days, I’m currently working on a new app that involves transmitting a fairly large amount of data from an iPhone app (WingsuitGP) to a backend web server. This is sort of backwards from what people are usually doing with JSON. Typically, JSON data is created by backend web services and then consumed by mobile apps. But in my case, my mobile app is the one creating the JSON data, and my backend web service is the consumer of the JSON data.
To transmit my JSON data over the network, I’m currently using the Alamofire http networking library/wrapper for iOS. With Alamofire, JSON data needs to be created first in the form of a Swift Dictionary which is then later converted to JSON format by Alamofire before being sent over the network via http.
One speed bump which I’ve run into so far is generating JSON friendly dictionaries in Swift dynamically. For example, lets say I have a large amount of data stored in the form of objects in my client-side Realm Database, how do I go about programmatically iterating over all of my data to dynamically create a Swift Dictionary that is also ready for conversion to JSON format by Alamofire? I’ve found some fairly straightforward examples on how to properly create JSON friendly swift dictionaries that are hard-coded, but I haven’t really been able to find any examples on how to dynamically create these dictionaries using an undetermined amount of data. So… here I present the solution I’ve hacked together today on repl.it (the solution shows the hard-coded method along with the dynamically generated method):
import Foundation // REFERENCE: https://dzone.com/articles/all-you-need-to-know-about-json-with-swift // Create a Hard-Coded Dictionary (JSON Friendly) var myDictionary = [ "location": [ [ "latitude": 30.00000001, "longitude": 30.0000005, "timestamp": 2342342342 ], [ "latitude": 30.00000029, "longitude": 30.00000023, "timestamp": 2342342343 ] ], "altitude": [ [ "pressure": 90.00000001, "timestamp": 2342342345 ], [ "pressure": 91.00000029, "timestamp": 2342342347 ] ] ] as [String:Any] print("Hard-Coded Dictionary (JSON FRIENDLY)") print(myDictionary) print("") // Create a Dynamically Generated Dictionary (ALSO JSON FRIENDLY) var myNewDictionary = [:] as [String:Any] var myLocationArray: [Int:Any] = [:] myLocationArray[0] = [ "latitude": 30.00000001, "longitude": 30.0000005, "timestamp": 2342342342 ] myLocationArray[1] = [ "latitude": 31.00000001, "longitude": 31.0000005, "timestamp": 2542342342 ] var myAltitudeArray: [Int:Any] = [:] myAltitudeArray[0] = [ "pressure": 90.00000001, "timestamp": 2342342342 ] myAltitudeArray[1] = [ "pressure": 91.00000001, "timestamp": 2542342342 ] myNewDictionary["location"] = myLocationArray myNewDictionary["altitude"] = myAltitudeArray print("Dynamically Generated Dictionary (ALSO JSON FRIENDLY)") print(myNewDictionary)