10.7. Posting Data with AlamoFire: POST

http://apis.sakibnm.space:8888/contacts/text/add

Now it's time to add a new contact. We need to read the name, email, and phone number the user puts into the bottom add view. Then when the user taps the Add Contact button, we need to use Alamofire to post the data to the API server.

Fetching the user inputs and creating a new Contact object

Let's open ViewController.swift file. Then add an action to mainScreen.buttonAdd (Add Contact button):

//
//  ViewController.swift
//  App10
//
//  Created by Sakib Miazi on 5/25/23.
//

import UIKit
import Alamofire

class ViewController: UIViewController {
    
    //codes omitted...
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //codes omitted...
        
        //MARK: add action to Add Contact button...
        mainScreen.buttonAdd.addTarget(self, action: #selector(onButtonAddTapped), for: .touchUpInside)
    }
    
    //MARK: on Add Contact button tapped...
    @objc func onButtonAddTapped(){
        
    }
    
    //MARK: add a new contact call: add endpoint...
    func addANewContact(contact: Contact){
        
    }
}

Now let's define a struct Contact in a separate file. We will use this struct to create Swift contact objects for the API contacts.

Now, onButtonAddTapped() method, we will fetch the values from the text fields of the bottom add view. Let's write following code in onButtonAddTapped():

We unwrapped the optional values from the text fields and fetched the strings. Then we convert the phone number's text to an integer.

Making the API call for the endpoint 'add.'

We need to use Alamofire to POST the new contact we created above to the server. We now write the following code in addANewContact(contact: Contact) method:

In the above code:

  • We use Alamofire to create a POST request (at line 5) and add the body parameters. In the Postman testing, we used body form parameters to send data to post to the API server, right? We create a dictionary to create key-value pairs here in Alamofire and post them with the request.

  • The handler closure is pretty straightforward. We first check if there is any network error or not. If the network is OK, then we check the status code. If the code is 200-level, we know that our request was valid and the response is desirable.

    • If it is a 200-level code, we will get the updated contacts by calling getAllContacts() again.

    • Also, we clear the text fields to empty after we complete adding the new user by calling clearAddViewFields() method.

If you are still with me, we are done with adding a new contact. Let's run the app again.

Yay! we are done adding a new contact!

Last updated

Was this helpful?