Codementor Events

How to use Alamofire and SwiftyJSON with Swift?

Published Jan 29, 2017
How to use Alamofire and SwiftyJSON with Swift?

Alamofire is an HTTP networking library written in Swift.

SwiftyJSON makes it easy to deal with JSON data in Swift.

Steps to setup the CocoaPods

  1. Open Terminal
  2. CocoaPods runs on ruby so update your system.
  sudo gem update --system
  1. Install CocoaPods

    Install CocoaPods by using following command :

  sudo gem install cocoapods

If you are facing issue in EL Capitan or macOS Sierra then use following command :

  sudo gem install -n /usr/local/bin cocoapods
  1. Setup the Pod
  pod setup

Note : This process will take some time.

Steps to add Alamofire and SwiftyJSON Pods to your project

  1. Open Terminal
  2. Navigate to the directory containing your AlamofireSwiftyJSONSample project by using the cd command:
  cd ~/Path/To/Folder/Containing/AlamofireSwiftyJSONSample
  1. Give the init command
  pod init

It will create Podfile in your project's directory.

  1. Open the Podfile using command
  open -a Xcode Podfile
  1. Edit the pod file with your pods which you want to use and must remember the targets. Add pods to the particular target where you want to use that pod.

In Swift you have to add one more line use_frameworks!

So, Your Podfile will look like as :

  platform :ios, '9.0'
  use_frameworks!

  target 'AlamofireSwiftyJSONSample' do
      pod 'Alamofire'
      pod 'SwiftyJSON'
  end

  target 'AlamofireSwiftyJSONSampleTests' do

  end

  target 'AlamofireSwiftyJSONSampleUITests' do

  end
  1. Go to terminal and give following command
  pod install

Note : From now you have to use the .xcworkspace of your project.

Let's use it in our project

Import it in your file where you want to use it.

  import UIKit
  import Alamofire
  import SwiftyJSON

  class ViewController: UIViewController {
  }

Here is simple get request URL : http://api.androidhive.info/contacts/ we will use it to get data from it via Alamofire.

  Alamofire.request("http://api.androidhive.info/contacts/").responseData { (resData) -> Void in
      print(resData.result.value!)
      let strOutput = String(data : resData.result.value!, encoding : String.Encoding.utf8)
      print(strOutput)
  }

Here we have used conversion of data to the String.

We can do batter and go easy with the SwiftyJSON.

  Alamofire.request("http://api.androidhive.info/contacts/").responseJSON { (responseData) -> Void in
      if((responseData.result.value) != nil) {
          let swiftyJsonVar = JSON(responseData.result.value!)
          print(swiftyJsonVar)
      }
  }

Let's Populate a table with the JSON response

Declaration of variables and outlets:

  @IBOutlet var tblJSON: UITableView!
  var arrRes = [[String:AnyObject]]() //Array of dictionary 

Fetch data from Request and reload the table:

Using Alamofire Version 2.0.2:

  override func viewDidLoad() {
      super.viewDidLoad()
      Alamofire.request(.GET, "http://api.androidhive.info/contacts/").responseJSON { (req, res, json) -> Void in
          let swiftyJsonVar = JSON(json.value!)

          if let resData = swiftyJsonVar["contacts"].arrayObject {
              self.arrRes = resData as! [[String:AnyObject]]
          }
          if self.arrRes.count > 0 {
              self.tblJSON.reloadData()
          }
      }
  }

Using Alamofire Version 3.3.1 :

Due to Alamofire Version 3 and syntax change old code not work.
You can check Alamofire 3.0 Migration Guide.

  override func viewDidLoad() {
      super.viewDidLoad()
      Alamofire.request(.GET, "http://api.androidhive.info/contacts/").responseJSON { (responseData) -> Void in
          if((responseData.result.value) != nil) {
              let swiftyJsonVar = JSON(responseData.result.value!)

              if let resData = swiftyJsonVar["contacts"].arrayObject {
                  self.arrRes = resData as! [[String:AnyObject]]
              }
              if self.arrRes.count > 0 {
                  self.tblJSON.reloadData()
              }
          }
      }
  }

Using Alamofire Version 4.0 :

Due to Alamofire Version 4 and syntax change old code not work.
You can check Alamofire 4.0 Migration Guide.

  override func viewDidLoad() {
      super.viewDidLoad()
      Alamofire.request("http://api.androidhive.info/contacts/").responseJSON { (responseData) -> Void in
          if((responseData.result.value) != nil) {
              let swiftyJsonVar = JSON(responseData.result.value!)

              if let resData = swiftyJsonVar["contacts"].arrayObject {
                  self.arrRes = resData as! [[String:AnyObject]]
              }
              if self.arrRes.count > 0 {
                  self.tblJSON.reloadData()
              }
          }
      }
  }

Delegate methods of table :

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
      let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("jsonCell")!
      var dict = arrRes[indexPath.row]
      cell.textLabel?.text = dict["name"] as? String
      cell.detailTextLabel?.text = dict["email"] as? String
      return cell
  }

  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return arrRes.count
  }

Conclusion

Populated-Table-via-Alamofire-and-SwiftyJSON.png

This is a Sample of Alamofire with SwiftyJSON on Github.

Check other articles/tutorials for iOS.

Thank you all the watchers ๐Ÿ˜ƒ
Happy Coding ๐Ÿ˜ƒ
Keep Learning, Following, Swifting ๐Ÿ˜‰

Discover and read more posts from Ashish Kakkad
get started
post commentsBe the first to share your opinion
Robin sharma
5 years ago

plzz tell me the code POST data also

Thiago Reis de Souza
5 years ago

Hi, I followed your procedure but did not get the expected result. I tested adapting to my scenario and I get the following message:

atal error: Unexpectedly found nil while implicitly unwrapping an Optional value
2019-09-04 21:01:28.228350-0300 Sivirino.com[3363:1890501] Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

Mohsen Abdollahi
5 years ago

Thanks Buddy ๐ŸŒน

Show more replies