How to use Alamofire and SwiftyJSON with Swift? – Swift 3 – iOS 10 – Xcode 8

Swift JSON
Swift JSON

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.

  3. Install CocoaPods

    Install CocoaPods by using following command :

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

  4. Setup the Pod

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:

  3. Give the init command

  4. It will create Podfile in your project’s directory.

  5. Open the Podfile using command

  6. 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 :

  7. Go to terminal and give following command

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.

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

Here we have used conversion of data to the String.

We can do batter and go easy with the SwiftyJSON.

Let’s Populate a table with the JSON response

Declaration of variables and outlets:

Fetch data from Request and reload the table:

Using Alamofire Version 2.0.2:

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.

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.

Delegate methods of table :

Conclusion

Populated Table via Alamofire and SwiftyJSON
Populated Table via Alamofire and SwiftyJSON

This is a Sample of Alamofire with SwiftyJSON on Github.

Check other articles/tutorials for Swift Language

I have added one more tutorial regarding the wrapper for Alamofire and SwiftyJSON : How to create a wrapper for Alamofire and SwiftyJSON? Swift – iOS

Thank you all the watchers 🙂
Happy Coding 🙂
Keep Learning, Following, Swifting 😉

  • mehmet

    Hi Ashish, I got error says expects one argument but 3 were specified for following line;

    Alamofire.request(.GET, “http://api.androidhive.info/contacts/”).responseJSON { (req, res, json) -> Void in

    • Make sure about the version. Version of Alamofire and Xcode.

      • GG

        i have the same problem with Xcode 7 and Alamofire 3.0.0+

        • This is example of the 2.0.3. So, I will update the article when I get time. I will check the issue in the 3.0 Version. Thanks.

        • I have updated the article with Alamofire Version 3.1.2. Hope it helps you.

    • I have updated the article with Alamofire Version 3.1.2. Hope it helps you.

  • Kevin Grzela

    Hi Ashish and thank you for the tutorial!

    Unfortunately I was unable to get the program to work. When run, the table appears empty. I verified that swiftyJsonVar and arrRes are being populated. I am on xCode 7.1.1 and testing on iOS 9.1

    Note: There is a warning that occurs saying: “Main.storyboard scene is unreachable due to lack of entry point and does not have an identifier for runtime access”

    • This is another error you have to check and resolve it.

      Thanks for complement.

  • What’s Taking place i’m new to this, I stumbled upon this I have found It absolutely useful and it has aided me out loads.
    I hope to contribute & aid other users like its helped me.
    Great job.

  • javad

    Hi Ashish .
    thank you for the tutorial!
    I am on xCode 7.2 and testing on iOS 9 and swift 2
    but table view empty and when that print (swiftyJsonVar) return :[]
    why ???

    • Your JSON response is not available I think. because it returns empty array. Check your webservice else post a question in stack overflow.

      Thanks a lot

  • This was so helpful thank you!

  • Joe

    Nice one

  • Tony Ricardo

    I got a Error in :

    let swiftyJsonVar = JSON(responseData.result.value!)

    fatal error: unexpectedly found nil while unwrapping an Optional value
    (lldb)

    so whats happen?

    Thanks.

    • Check response of your webservice is it a JSON response or you are getting error in your response.

      And just unwrap the response by if and let.

      It’s issue of webservice.

      Thanks for visiting the blog.

    • Tony Ricardo

      Ok i Fixed that, sorry about that!

      and thank you very much for the tutorial!

      • Yes. In iOS 9 this is the settings that you have to do.

        Thanks for visiting the blog.

      • Ayushman

        how did you fix it, i also got same error

  • Tony Ricardo

    You need to change your Plist . to allow Http … because they change the TransportSecurity!

    NSAppTransportSecurity

    NSExceptionDomains

    api.androidhive.info

    NSIncludesSubdomains

    NSExceptionAllowsInsecureHTTPLoads

    NSExceptionRequiresForwardSecrecy

    NSExceptionMinimumTLSVersion
    TLSv1.2
    NSThirdPartyExceptionAllowsInsecureHTTPLoads

    NSThirdPartyExceptionRequiresForwardSecrecy

    NSThirdPartyExceptionMinimumTLSVersion
    TLSv1.2
    NSRequiresCertificateTransparency

    Anyway, thanks bro

  • Tony Ricardo

    Do you have the Sample? is not working here, i made the XCode print the JSON and i got in console, but not in the Tableview!

    • Just you have to do the code for dumping data in table view.

  • Tony Ricardo

    Ok bro, can you delete my Commentaries? i got all the things!

    now i got the list and im consuming the JSON…

    you save my life man! i was very confused about many things and now with ur tutorial help me how to parse JSON and Cosuming the services!

    Thanks a lot bro! sorry about the questions!

  • I face small issue while I am trying excute this command
    sudo gem install cocoapods , as I am using El Captian after some researchs I found proper command do the same function
    sudo gem install -n /usr/local/bin cocoapods
    please mate mention this in your article

  • Teddy Kwak

    Please send me or upload to Github this tutorial sample code.

  • Ayushman

    if there is no “contacts” then how to parse other value?

    • If there is no contact then the array will be empty.

      • Ayushman

        I mean to say there is no word “contacts” only and there is other value left

        • Atleast you have to check your response that what field you want to fetch.

          • chetan regmi

            {

            “id”: “c200”,

            “name”: “Ravi Tamada”,

            “email”: “ravi@gmail.com”,

            “address”: “xx-xx-xxxx,x – street, x – country”,

            “gender” : “male”,

            “phone”: {

            “mobile”: “+91 0000000000”,

            “home”: “00 000000”,

            “office”: “00 000000”

            }

            },

            {

            “id”: “c201”,

            “name”: “Johnny Depp”,

            “email”: “johnny_depp@gmail.com”,

            “address”: “xx-xx-xxxx,x – street, x – country”,

            “gender” : “male”,

            “phone”: {

            “mobile”: “+91 0000000000”,

            “home”: “00 000000”,

            “office”: “00 000000”

            }

            how to fetch data if the json format is like this

  • aholtzman

    I am trying to use this as a guide for accessing this API http://api.bandsintown.com/artists/JoeFletcherAndTheWrongReasons/events.json?api_version=2.0&app_id=LBB_APPS

    I am hitting trouble where at this point in the code – if let resData = swiftyJsonVar[“contacts”].arrayObject – there is no equivalent to the “contacts” in the JSON I am getting. How do I work with/around this?

    I am new to development, sorry if this is a simple question.

    • chetan regmi

      there is no “contacts” in http://api.bandsintown.com/artists/JoeFletcherAndTheWrongReasons/events.json?api_version=2.0&app_id=LBB_APPS
      once check the url and check the word “contacts” there is no contacts

      • Ashish Kakkad

        Yes. You are right chetan.

      • aholtzman

        my question… how do I use this guide you have created for an API that starts with an array “[” rather than a dictionary as the JSON does for the code above?

        • chetan regmi

          if it is “[” then start with 0 like example if json is like this:

          [

          {

          “id” : 123,

          “first_name” : “Chetan”,

          “last_name” : “Regmi”

          },

          {

          “id” : 123,

          “first_name” : “Aholtz”,

          “last_name” : “Man”

          }

          ]

          then use like this

          Alamofire.request(.GET, “your url here”).responseJSON { (responseData) -> Void in

          if((responseData.result.value) != nil) {

          let swiftyJsonVar = JSON(responseData.result.value!)

          print(swiftyJsonVar[0][“first_name”])

          }

          }

          print(swiftyJsonVar[0][“title”][“rendered”])

          • chetan regmi

            type numeric zero as it looks like “o” here

          • aholtzman

            That solved it. Thank you.

    • Ashish Kakkad

      You have to understand the concept that why I have written the “contacts” there. It’s available as a field in the output. Check your output.

    • Ashish Kakkad

      You have to understand the concept that why I have written the “contacts” there. It’s available as a field in the output. Check your output.

  • D.D

    Hi Ashish,

    This tutorial has been very helpful. Can you explain how to get an image displayed in the table if the image url is part of the information stored in the json?

    • Ashish Kakkad

      For Images You Can Use Kingfisher Pod. It’s available on github.

      • D.D

        Thanks!

      • D.D

        Thanks!

  • Arafin Mac Russell

    it helped me a lot 🙂 , thank you so much …

    • Ashish Kakkad

      Thanks to you too.

  • D.D

    Hi Ashish,

    Great update for swift 3.0. Everything works great but I do have a question that I’m hoping you can help with. I am adding a method to pull additional JSON data from other pages on my website and add the results downloaded to the arrRes to add more cells to the table.

    The method is initiated by pushing a button and so far I’ve gotten to the point of being able to pull and store the new JSON data in a new variable arrRes2, but I am unsure of how to merge the new results (arrRes2) with the initial results (arrRes).

    • D.D

      i asked too soon. Just figured it out.

  • D.D

    Hi Ashish,

    I’m getting an error with swift 3.0 that i wasn’t getting earlier with 2.1 when i try to get results from my JSON data

    the line of code looks like this:

    let urlString = dict[“data”]![“featured_image”]!![“rendered”] as? String

    the error i get now is : “Type ‘Any’ has no subscipt members”

    I didn’t have a problem with that line until I updated Xcode and switched to swift 3.0. Do you know why this is happening?

    Cheers

  • Anami Gosai

    Hello.
    For the same example, I want to fetch data of “phone”: {

    “mobile”: “+91 0000000000”,

    “home”: “00 000000”,

    “office”: “00 000000”

    }
    for all the fields. And I am not able to fetch it.
    can you please provide me solution of this?

    My code:

    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]]

    print(“Array == (self.arrRes)”)

    let details = resData[“phone”] as! [[[String:AnyObject]]]

    print(“Phone Number == (details)”)

    }

    if self.arrRes.count > 0

    {

    self.tableView.reloadData()

    }

    }

    }

    and Error is: Cannot subscript a value of type ‘[Any]’ with an index of type ‘String’ at line:let details = resData[“phone”] as! [[[String:AnyObject]]]