Taking a Third Look at Creating JSON Friendly Dictionaries in Swift

So working with JSON in Swift has me stumped! I’ve been trying like hell to create large JSON objects in Swift but keep running into the same problem: Not everything you can write in pure JSON can be re-written with Swift Dictionaries. The networking libary which I’m currently using, Alamofire, expects you to write your JSON using Swift Dictionaries, and then the library/wrapper converts everything into JSON for you before sending it over the network using the HTTP POST method.
However, I think I’ve figured out the missing work-around. Well actually… someone on StackOverflow has figured out the missing work-around: How to make HTTP Post request with JSON body in Swift
Now, not everything in the blog post is relevant to what I’m trying to do as they are working with URLSession instead of Alamofire to handle the networking. But, I noticed one very interesting thing in the answers section that leads me to believe I’ve found the missing work-around. Here is how one StackOverflow user wrote his JSON:

let json: [String: Any] = [
    "title": "ABC",
    "dict": [
        "1":"First",
        "2":"Second"
    ]
]


Notice, he uses numbers for keys (as I would like to do) and is able to get away with this by cleverly wrapping the numbers in quotes to create a string! Sort of a hacked-together work around, but I think this is what I’ve been missing! Now all I have to do is cast the indexes in my arrays of data as strings and I’m good to go! Looks like things are headed in the right direction 🙂

 

Sending JSON Data from an iOS App to a Backend Server Running PHP with the Alamofire Networking Library/Wrapper

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

For the past several days I’ve been trying to figure out how to send JSON data from an iOS app to a backend server running PHP (using the Alamofire networking library/wrapper). The problem that I seem to keep running into is that working with JSON in Swift is sort of a pain in the ass. With Alamofire you are suppose to construct a dictionary to represent your JSON data, and then using the Alamofire.request method you can easily send your data accross the networking using HTTP POST.
However, I keep running into problems when attempting to generate my JSON data dynamically. For example, let’s say I want to create a JSON object that contains thousands of pieces of information. Swift doesn’t make that easy! So far I’ve only been able to get everything to work if my JSON data is all hard-coded, and not generated dynamically.
I feel like I’m getting closer to the answer, but still am not quite where I want to be. So far this is what I have:
Single View (Main.storyboard)
SingleView

ViewController.swift

//
//  ViewController.swift
//  JSONxAlamofire
//
//  Created by Christopher Pedersen on 3/3/19.
//  Copyright © 2019 Christopher Pedersen. All rights reserved.
//
import UIKit
import Foundation
import Alamofire
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    @IBAction func onButtonClick(_ sender: Any) {
        let parameters: Parameters = [
            "firstTypeOfData": [
                ["foo": Int.random(in: 1...100), "bar": Int.random(in: 1...100), "baz": Int.random(in: 1...100)],
                ["foo": Int.random(in: 1...100), "bar": Int.random(in: 1...100), "baz": Int.random(in: 1...100)],
                ["foo": Int.random(in: 1...100), "bar": Int.random(in: 1...100), "baz": Int.random(in: 1...100)],
                ["foo": Int.random(in: 1...100), "bar": Int.random(in: 1...100), "baz": Int.random(in: 1...100)],
                ["foo": Int.random(in: 1...100), "bar": Int.random(in: 1...100), "baz": Int.random(in: 1...100)]
            ],
            "secondTypeOfData": [
                ["foo": Int.random(in: 1...100), "bar": Int.random(in: 1...100)],
                ["foo": Int.random(in: 1...100), "bar": Int.random(in: 1...100)],
                ["foo": Int.random(in: 1...100), "bar": Int.random(in: 1...100)],
                ["foo": Int.random(in: 1...100), "bar": Int.random(in: 1...100)],
                ["foo": Int.random(in: 1...100), "bar": Int.random(in: 1...100)]
            ]
        ]
        Alamofire.request("http://wingsuitgp.com/networkingtest.php", method: .post, parameters: parameters, encoding: JSONEncoding.default).response { response in
            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                print("Server Repsonse: \(response)") // print server response to console
            } else {
                print("ERROR: PC LOAD LETTER") // cryptic error message
            }
        }
    }

networkingtest.php

// Receive JSON Data Via HTTP POST
$data = json_decode(file_get_contents('php://input'));
$numberOfDataPoints = count($data->{'firstTypeOfData'});
if ($numberOfDataPoints <= 1) {     die("no data detected..."); } // Connect to MySQL Database $servername = "localhost"; $username = "DATABASE-ADMIN-NAME-GOES-HERE"; $password = "DATABASE-PASSWORD-GOES-HERE"; $dbname = "DATABASE-NAME-GOES-HERE"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
// Insert First Type of Data into MySQL Database
for ($i = 0; $i < $numberOfDataPoints; $i++){     $datatype = "first_type_of_data"; 	$foo = $data->{'firstTypeOfData'}[$i]->{'foo'};
	$bar = $data->{'firstTypeOfData'}[$i]->{'bar'};
	$baz = $data->{'firstTypeOfData'}[$i]->{'baz'};
	$stmt = $conn->prepare("INSERT INTO networkingtest_table (datatype_column, foo_column, bar_column, baz_column) VALUES (?, ?, ?, ?)");
	$stmt->bind_param("siii", $datatype, $foo, $bar, $baz);
	$stmt->execute();
    $stmt->close();
}
// Insert Second Type of Data into MySQL Database
for ($i = 0; $i < $numberOfDataPoints; $i++){     $datatype = "second_type_of_data"; 	$foo = $data->{'secondTypeOfData'}[$i]->{'foo'};
	$bar = $data->{'secondTypeOfData'}[$i]->{'bar'};
    $baz = 0;
	$stmt = $conn->prepare("INSERT INTO networkingtest_table (datatype_column, foo_column, bar_column, baz_column) VALUES (?, ?, ?, ?)");
	$stmt->bind_param("siii", $datatype, $foo, $bar, $baz);
	$stmt->execute();
    $stmt->close();
}
// Close MySQL Database Connection
$conn->close();
echo "data_received"; // echo server response back to client iPhone app
 

App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure

“App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure”– quite the annoying error message eh? Okay, to fix this error and get on with your life using HTTP instead of HTTPS, you just need to add a little XML code to your Info.plist file and all will be well…
Add This Snippet of XML to Your Info.plist File (Github Gist) 
Reference This Complete Info.plist File For Context (Github Gist)

 

The Problem with Equity Crowdfunding

As the founder of an early stage startup (WingsuitGP), early stage startup funding is of great interest to myself. Isn’t that every aspiring internet entrepreneurs dream? To obtain that very first investment of outside capital, enough to quit your day-job and start working on your passion project full time.
With that in mind, I recently reached out to one of the big players in equity crowdfunding– AngelList backed Republic.co. Specifically, my question for the team at Republic was, “how much does it actually cost to raise money on Republic?” While it looks like many of the costs of raising money through equity crowdfunding portals can be deferred until after the fund raise is over, unfortunately the upfront costs (AKA onboarding costs) are substantial, somewhere between $3,000 to $10,000. And these upfront “onboarding costs” cannot be deferred until after a fund raise is complete.
So maybe this is why equity crowdfunding hasn’t really taken off yet. Raising $100,000 on the internet for your early stage startup sounds amazing. But once you throw in the $3,000 to $10,000 in costs required to run such a funding campaign, the idea seems significantly less appealing. Essentially, you need an outside investor first if you want to raise money on one of these crowdfunding portals. And more likely, you need fairly big first check in of initial seed investing. Because if an angel were to take a chance on you and write you a $20,000 check, why would you gamble half of that on a running an equity crowdfunding campaign that might fail?
And unfortunately, I think what these portals are actually ending up with are companies that have received a fair amount of initial funding, and are coming to the portals with their last $10,000 running hail-mary campaigns to try and cash in one last round of funding before their company implodes. I mean seriously, are there any hot startups raising money on these platforms? I could be wrong, but I think the problem is simple: The upfront “onboarding” fees that these portals charge are too high to make them competitive with raising money from traditional angel investors and startup accelerators like Y Combinator. Think about it, how many people would go through YC’s program if instead of receiving funding from YC and also getting the chance to pitch investors at demo day, the startups had to pay YC $3,000 to $10,000 for the chance to go and pitch at demo day? Startups don’t need expenses; they need investments. I honestly hope that the crowdfunding platforms get things figured out, but at the moment these fees are going to continue ensuring that they miss out on the up and coming startups and end up with all of the previously funded but now failing startups.

 

Marc Andreessen & Brendan Baker on Traction

Tonight I happened to stumble upon a great blog post from Venture Hacks titled What should I send investors? Part 3: Business Plans, NDAs, and Traction. The post cites two other blog posts, one from Marc Andreessen and another from Brendan Baker. I really wanted to read the aforementioned posts but unfortunately the links had long ago rotted away. Luckily I was able to find the posts elsewhere and just wanted to bookmark them here. Enjoy!
Part 4: The only thing that matters by Marc Andreessen
Startups: How to Communicate Traction to Investors by Brendan Baker

 

Taking a Second Look at Creating JSON Friendly Dictionaries in Swift

Earlier today I published a bunch of blog posts on how to create dictionaries in Swift that can easily be turned into JSON using the Alamofire networking library/wrapper for iOS. While I was trying to figure all of this stuff out earlier today I was primarily using the web based repl.it environment. However, after taking a second look at things it looks like using repl.it to do all of my testing may have been one of the big reasons why my solution ended up being much more complex than I would have imagined necessary.
After taking a step back and approaching the problem with a fresh perspective, it appears Alamofire has a built in class called “Parameters” which makes it easy to create JSON friendly dictionaries in Swift. Apparently however, I didn’t attempt to use this convenient class because I was doing all my hacking in the web browser and the actual Alamofire library and Parameters class was not available to me. So now I know: just use the Parameters class and creating JSON objects in Swift shouldn’t be all that complicated (maybe a little complicated, but not too bad).

 

Dynamically Generating JSON Friendly Dictionaries in Swift

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)

 

Representing JSON Data in the Form of Swift Dictionaries

The project which I’m currently working on involves working with a lot of JSON data in an iOS mobile app which I plan on sending to a database using the Alamofire http networking library/wrapper. When working with JSON in Swift using Alamofire, you need to create your JSON objects in the form of Swift Dictionaries. This has been pretty confusing for me, so I wanted to whip up this quick blog post for my own personal reference demonstrating how to represent JSON data in the form of a Swift Dictionary so that it can later be sent over the internet to a backend server using Alamofire:
exampledata.json

{
    "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
        }
    ]
}

 
exampledictionary.swift

import Foundation
// REFERENCE: https://dzone.com/articles/all-you-need-to-know-about-json-with-swift
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(myDictionary)

 
REFERENCE: All You Need to Know About JSON With Swift

 

Working with JSON in PHP: Accessing Array Items

This afternoon I spent a little time playing around with JSON & PHP using repl.it so that I can figure out how to build the next part of my WingsuitGP app. For this app I’m sending a fairly large amount of JSON data from an iPhone app back to a server running PHP, and need to parse all of the JSON data so that I can stick it in a MySQL database for further analysis. Not sure if this will be of any use to anyone other than myself, but here is what I have so far:

$rawJSON = '
{
    "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
        }
    ]
}
';
$decodedJSON = json_decode($rawJSON);
$latitude[0] = $decodedJSON->{'location'}[0]->{'latitude'};
$longitude[0] = $decodedJSON->{'location'}[0]->{'longitude'};
$locationTimestamp[0] = $decodedJSON->{'location'}[0]->{'timestamp'};
$latitude[1] = $decodedJSON->{'location'}[1]->{'latitude'};
$longitude[1] = $decodedJSON->{'location'}[1]->{'longitude'};
$locationTimestamp[1] = $decodedJSON->{'location'}[1]->{'timestamp'};
$altitude[0] = $decodedJSON->{'altitude'}[0]->{'pressure'};
$altitudeTimestamp[0] = $decodedJSON->{'altitude'}[0]->{'timestamp'};
$altitude[1] = $decodedJSON->{'altitude'}[1]->{'pressure'};
$altitudeTimestamp[1] = $decodedJSON->{'altitude'}[1]->{'timestamp'};
echo "\n";
echo "Latitude Point 0: {$latitude[0]}" . "\n";
echo "Longitude Point 0: {$longitude[0]}" . "\n";
echo "Location Timestamp 0: {$locationTimestamp[0]}" . "\n";
echo "\n";
echo "Latitude Point 1: {$latitude[1]}" . "\n";
echo "Longitude Point 1: {$longitude[1]}" . "\n";
echo "Location Timestamp 1: {$locationTimestamp[1]}" . "\n";
echo "\n";
echo "Altitude Reading 0: {$altitude[0]}" . "\n";
echo "Altitude Timestamp 0: {$altitudeTimestamp[0]}" . "\n";
echo "\n";
echo "Altitude Reading 1: {$altitude[1]}" . "\n";
echo "Altitude Timestamp 1: {$altitudeTimestamp[1]}" . "\n";
echo "\n";

 

Swift Objects, JSON, & Making HTTP POST Requests with Alamofire

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

Another little note to self tonight, this time regarding how to convert swift objects to JSON in order to make HTTP POST requests using the Alamofire networking library/wrapper: When making HTTP POST requests using the JSON data format with Alamofire, you actually need to turn your swift objects into dictionaries, then you can pass the dictionary to Alamofire and it will handle converting your dictionary into JSON. I was under the assumption that you could just pass Alamofire an object since JSON stands for JavaScript Object Notation and not JavaScript Dictionary Notation, but Alamofire apparently wants a dictionary. This didn’t really seem obvious to me so… that’s why I’m making note of this here on my dev-blog. And here is a link to the original StackOverflow where I found the answer to this question: [Send] Object as Parameter using Alamofire
Note, while the code example below does work, there is a small bug involving the forced unwrapping of an optional that I should not have unwrapped. However, for demonstration/reference purposes, I think it’s a pretty good example (Also, you will need to make sure to add a little XML to your Info.plist if you would like to use HTTP instead of HTTPS):

//
//  ViewController.swift
//  NetworkingWithJSON
//
//  Created by Christopher Pedersen on 3/1/19.
//  Copyright © 2019 Christopher Pedersen. All rights reserved.
//
import UIKit
import Alamofire
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    @IBAction func onPostJsonButtonClicked(_ sender: Any) {
        let exampleObject = ExampleClass()
        let exampleDictionary: [String:String] = [
            "id_column": "\(exampleObject.firstExampleProperty)",
            "mediumtext_column": "\(exampleObject.secondExampleProperty)"
        ]
        let parameters = exampleDictionary
        Alamofire.request("http://wingsuitgp.com/networkingwithjson.php", method: .post, parameters: parameters, encoding: JSONEncoding.default).response { response in
            print("Request: \(response.request!)")
            print("Request \(response.response!)")
            print("Error: \(response.error!)")
            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                print("Data: \(utf8Text)")
            }
        }
    }
}


//
//  ExampleClass.swift
//  NetworkingWithJSON
//
//  Created by Christopher Pedersen on 3/1/19.
//  Copyright © 2019 Christopher Pedersen. All rights reserved.
//
import Foundation
class ExampleClass {
    var firstExampleProperty: String = "ObjectConvertedToDictConvertedToJSON"
    var secondExampleProperty: String = "AlamofireSaysHello"
}