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

 

topherPedersen