Swift: Handling JSON with Alamofire & SwiftyJSON

alamofire json parsing swift 5
alamofire json parsing swift 4
alamofire swiftui
response.result.value alamofire 5
alamofire-swiftyjson
alamofire post request swift 5
alamofire responsejson
alamofire 5 tutorial

This is sure to be asked several times, but I have not yet found the right answer, although I have been looking very hard.

I use Alamofire and SwiftyJSON and my JSON data looks like that:

{
  "528" : {
    "name" : "Name 1",
    "id" : "528",
    "product_id" : null,
    "visible" : "0",
    "level" : "2"
  },
  "29" : {
    "name" : "Name 2",
    "id" : "29",
    "product_id" : null,
    "visible" : "1",
    "level" : "1"
  },
  "173" : {
    "name" : "Name 3",
    "id" : "173",
    "product_id" : null,
    "visible" : "0",
    "level" : "2"
  },
  "143" : {
    "name" : "Name 4",
    "id" : "143",
    "product_id" : null,
    "visible" : "1",
    "level" : "2"
  },

...with this code:

Alamofire.request(.GET, dataURL, parameters: nil, encoding: .JSON)

    .responseJSON { (request, response, jsonData, error) in

        let json = JSON(jsonData!) 

        println(json)

    }

...so everything should be fine with JSON

  1. How can i access to that data? I mean how can i get names, ids, product_ids etc

  2. How can i put that data (name) to my TableViewController?

I am using both SwiftyJSON and Alamofire in one of my projects. Here is how I am using it.

  1. Create a protocol called APIProtocol.
  2. Setup an API class with a GET method that accepts a delegate of type APIProtocol.
  3. Setup TableViewController to implement the APIProtocol.
  4. Call API.get() from TableViewController
Code
// Step 1
protocol APIProtocol {
  func didReceiveResult(results: JSON)
}

// Step 2
func get(path: String, parameters: [String: AnyObject]? = nil, delegate: APIProtocol? = nil){
  let url = "\(self.hostname)\(path)"
  NSLog("Preparing for GET request to: \(url)")

  Alamofire.request(.GET, url, parameters: parameters)
    .responseJSON { (req, res, json, error) in
      if(error != nil) {
        NSLog("GET Error: \(error)")
        println(res)
      }
      else {
        var json = JSON(json!)
        NSLog("GET Result: \(json)")

        // Call delegate if it was passed into the call
        if(delegate != nil) {
            delegate!.didReceiveResult(json)
        }
      }
    }
}

// Step 3
class ActivityViewController: UITableViewController, APIProtocol {
  var activityModelList: NSMutableArray = [] // This is the array that my tableView is using.

  ... 

  func didReceiveResult(result: JSON) {
    var activities: NSMutableArray = []

    NSLog("Activity.didReceiveResult: \(result)")

    for (index: String, activity: JSON) in result {

      var activityModel = ActivityModel(
        id: activity["id"].intValue,
        message: activity["message"].stringValue
      )

      activities.addObject(activityModel)
    }

    // Set our array of new models
    activityModelList = activities

    // Make sure we are on the main thread, and update the UI.
    dispatch_sync(dispatch_get_main_queue(), {
      self.refreshControl!.endRefreshing()
      self.tableView.reloadData()
    })
  }
}

// Step 4
override func viewDidLoad() {
  MyAPI.get("/activities", delegate: self)
}

Alamofire 5 Tutorial for iOS: Getting Started, Alamofire is a third party networking library that helps with tasks such as SwiftyJSON is a Swift library for reading and processing JSON data. Alamofire Tutorial with Swift (Quickstart) By Francis Fuerte and Chris Ching Last updated Nov 20, 2019 If you have been diving deep into iOS development you may have already come across accessing data/databases using URLSession , this is fine and all but sometimes it gets annoying to use, this is where Alamofire comes in.

The accessors (for SwiftyJSON at least) work like:

if let userName = json[0]["528"]["name"].string{
    println(userName) // "Name 1"
}

More information on how to use SwiftyJSOn can be found here in its official documentation: https://github.com/SwiftyJSON/SwiftyJSON

Regarding how to put that data into a UITableView, there are many methods. Set up a UITableView cell and then load in the JSON data in some sort of array for instance.

Alamofire Tutorial: Getting Started, Swift Tutorial: API integration using Alamofire using swift 5 with JSON name, capital and Duration: 27:44 Posted: Jan 29, 2020 Alamofire is a Swift-based HTTP networking library for iOS and macOS. It provides an elegant interface on top of Apple’s Foundation networking stack that simplifies a number of common networking tasks. Alamofire provides chainable request/response methods, JSON parameter and response serialization, authentication, and many other features.

Check this repo for an example that declare how to use Alamofire in your code and how to create models with swift and parsing JSON response

  1. Install Alamofire in your project
  2. Import Alamofire in your class
  3. Define these variables in you class

    typealias complitionBlock = (data: AnyObject) -> Void
    
    let KBASE_URL: String = "http://static.westwing.de/cms/dont-delete/programming_task/data.json"
    
  4. Set the implementation for this function

    func getMainItems(complition block: complitionBlock) {
    
    Alamofire.request(.GET, KBASE_URL, parameters:nil).responseJSON { response in
    
         do {
            let items = try NSJSONSerialization.JSONObjectWithData(response.data!, options: NSJSONReadingOptions()) as! NSArray
    
             let mutableArray: NSMutableArray = []
    
             items.enumerateObjectsUsingBlock({ object, index, stop in
                 let str = object as! NSDictionary
                 //Replace WESItem with your model
                 //let item = WESItem(dictionary: str as NSDictionary)
                 mutableArray.addObject(item)
             })
             block(data: mutableArray)
         } catch {
             print(error)
         }
     }
    }
    

For more information: https://github.com/AhmedAskar/WestWing

Alamofire Tutorial with Swift (Quickstart), Sometimes the code gets really messy in Swift while parsing complex JSON data. Using SwiftyJSON library will help you to use JSON in Swift� Swift iOS app building tutorials with a focus on working with JSON APIs and getting things done Alamofire 5 will include support for handling Decodable responses. Until then, we need to handle turning Alamofire responses into our Codable types ourselves.

Following should work for you :-

           var nameArr = [String]() 

            Alamofire.request(.GET,"your url", parameters: nil)
                      .validate().responseJSON { response in
                         if let responseJson = response.result.value {
                           let name = responseJson["name"] as! String
                           nameArr.append(name)
                          }

                            dispatch_async(dispatch_get_main_queue(), {
                            self.tableView.reloadData()
                            })
                     }// Alamofire Close




 Use tableview as you normally use it i.e.

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("cell")

        if cell == nil {
            cell = UITableViewCell(style: .Default, reuseIdentifier: "cell")
        }

        cell!.textLabel?.text = nameArr[indexPath.row]
        return cell!
    }

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

Note: No need to use Swifty JSON as Alamofire allows JSON response which can be directly handled within ".responseJSON".

Swift Tutorial: API integration using Alamofire using swift 5 with , Open up ViewController.swift and take a look at the code provided. Inside of the Alamofire.request() closure, parse the JSON to to grab a random movie from� 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 Open Terminal CocoaPods runs on ruby so update your system. sudo gem update --system Install CocoaPods Install CocoaPods by using following command : sudo gem install cocoapods If you are Read more How to use Alamofire and SwiftyJSON with Swift

pod 'Alamofire' pod 'SwiftyJSON' pod 'ReachabilitySwift'

import UIKit import Alamofire import SwiftyJSON import SystemConfiguration

class WebServiceHelper: NSObject {

typealias SuccessHandler = (JSON) -> Void
typealias FailureHandler = (Error) -> Void

// MARK: - Internet Connectivity

class func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
    zeroAddress.sin_family = sa_family_t(AF_INET)

    guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
            SCNetworkReachabilityCreateWithAddress(nil, $0)
        }
    }) else {
        return false
    }

    var flags: SCNetworkReachabilityFlags = []
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
        return false
    }

    let isReachable = flags.contains(.reachable)
    let needsConnection = flags.contains(.connectionRequired)

    return (isReachable && !needsConnection)
}

// MARK: - Helper Methods

class func getWebServiceCall(_ strURL : String, isShowLoader : Bool, success : @escaping SuccessHandler, failure : @escaping FailureHandler)
{
    if isConnectedToNetwork() {

        print(strURL)

        if isShowLoader == true {

            AppDelegate.getDelegate().showLoader()
        }

        Alamofire.request(strURL).responseJSON { (resObj) -> Void in

            print(resObj)

            if resObj.result.isSuccess {
                let resJson = JSON(resObj.result.value!)

                if isShowLoader == true {
                    AppDelegate.getDelegate().dismissLoader()
                }

                debugPrint(resJson)
                success(resJson)
            }
            if resObj.result.isFailure {
                let error : Error = resObj.result.error!

                if isShowLoader == true {
                    AppDelegate.getDelegate().dismissLoader()
                }
                debugPrint(error)
                failure(error)
            }
        }
    }else {


        CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
    }
}

class func getWebServiceCall(_ strURL : String, params : [String : AnyObject]?, isShowLoader : Bool, success : @escaping SuccessHandler,  failure :@escaping FailureHandler){
    if isConnectedToNetwork() {

        if isShowLoader == true {
            AppDelegate.getDelegate().showLoader()
        }


        Alamofire.request(strURL, method: .get, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: {(resObj) -> Void in

            print(resObj)

            if resObj.result.isSuccess {
                let resJson = JSON(resObj.result.value!)

                if isShowLoader == true {
                    AppDelegate.getDelegate().dismissLoader()
                }

                success(resJson)
            }
            if resObj.result.isFailure {
                let error : Error = resObj.result.error!

                if isShowLoader == true {
                    AppDelegate.getDelegate().dismissLoader()
                }

                failure(error)
            }

        })
    }
else {

        CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
}

}



class func postWebServiceCall(_ strURL : String, params : [String : AnyObject]?, isShowLoader : Bool, success : @escaping SuccessHandler, failure :@escaping FailureHandler)
{
    if isConnectedToNetwork()
    {

        if isShowLoader == true
        {
            AppDelegate.getDelegate().showLoader()
        }

        Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: {(resObj) -> Void in

            print(resObj)

            if resObj.result.isSuccess
            {
                let resJson = JSON(resObj.result.value!)

                if isShowLoader == true
                {
                    AppDelegate.getDelegate().dismissLoader()
                }

                success(resJson)
            }

            if resObj.result.isFailure
            {
                let error : Error = resObj.result.error!

                if isShowLoader == true
                {
                    AppDelegate.getDelegate().dismissLoader()
                }

                failure(error)
            }
        })
    }else {
        CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
    }
}


class func postWebServiceCallWithImage(_ strURL : String, image : UIImage!, strImageParam : String, params : [String : AnyObject]?, isShowLoader : Bool, success : @escaping SuccessHandler, failure : @escaping FailureHandler)
{
    if isConnectedToNetwork() {
        if isShowLoader == true
        {
            AppDelegate.getDelegate().showLoader()
        }

        Alamofire.upload(
            multipartFormData: { multipartFormData in
                if let imageData = UIImageJPEGRepresentation(image, 0.5) {
                    multipartFormData.append(imageData, withName: "Image.jpg")
                }

                for (key, value) in params! {

                    let data = value as! String

                    multipartFormData.append(data.data(using: String.Encoding.utf8)!, withName: key)
                    print(multipartFormData)
                }
            },
            to: strURL,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        debugPrint(response)
                        //let datastring = String(data: response, encoding: String.Encoding.utf8)
                       // print(datastring)
                    }
                case .failure(let encodingError):
                    print(encodingError)
                    if isShowLoader == true
                    {
                        AppDelegate.getDelegate().dismissLoader()
                    }

                    let error : NSError = encodingError as NSError
                    failure(error)
                }

                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { (response) -> Void in

                        if response.result.isSuccess
                        {
                            let resJson = JSON(response.result.value!)

                            if isShowLoader == true
                            {
                                AppDelegate.getDelegate().dismissLoader()
                            }

                            success(resJson)
                        }

                        if response.result.isFailure
                        {
                            let error : Error = response.result.error! as Error

                            if isShowLoader == true
                            {
                                AppDelegate.getDelegate().dismissLoader()
                            }

                            failure(error)
                        }

                    }
                case .failure(let encodingError):
                    if isShowLoader == true
                    {
                        AppDelegate.getDelegate().dismissLoader()
                    }

                    let error : NSError = encodingError as NSError
                    failure(error)
                }
            }
        )
    }
    else
    {
        CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
    }
}
}

================================== 

Call Method

let aParams : [String : String] = ["DeviceIDString", "DeviceType" : "iOS", ]

        WebServiceHelper.postWebServiceCall(Constants.BaseURL, params: aParams as [String : AnyObject]?, isShowLoader: true, success: { (responceObj) in


            if "\(responceObj["RespCode"])" != "1"
            {
                let alert = UIAlertController(title: Constants.kAppName, message: "\(responceObj["RespMsg"])", preferredStyle: UIAlertControllerStyle.alert)
                let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
                }
                alert.addAction(OKAction)
                self.present(alert, animated: true, completion: nil)
            }
            else
            {
                let aParams : [String : String] = [
                    "Password" : self.dictAddLogin[AddLoginConstants.kPassword]!,
                    ]
                CommonMethods.saveCustomObject(aParams as AnyObject?, key: Constants.kLoginData)

            }
            }, failure:
            { (error) in

                CommonMethods.showAlertWithError(Constants.kALERT_TITLE_Error, strMessage: error.localizedDescription,withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
        })
    }

Swift 4 – How to use SwiftyJSON to deal with Alamofire , Work with Alamofire; Work with Moya; SwiftyJSON Model Generator. Why is the typical JSON handling in Swift NOT good? Swift is very strict about types. If both JSONs contain a value for the same key, mostly this value gets overwritten in the original JSON, but there are two cases where it provides some special treatment: In case of both values being a JSON.Type.array the values form the array found in the other JSON getting appended to the original JSON's array value.

API calls with Alamofire, Alamofire.request("https://httpbin.org/get").responseJSON { response in debugPrint(response) if let json = response.result.value { let ip� But these days lots of apps have tons of web service calls that are just begging for better handling, like a higher level of abstraction, concise syntax, simpler streaming, pause/resume, progress indicators, … In Objective-C, this was a job for AFNetworking. In Swift, Alamofire is our option for elegance.

SwiftyJSON/SwiftyJSON: The better way to deal with JSON , Once read into Swift, all JSON items are converted as follows: to handle NSDictionary or NSArray, or how to handle your JSON response using `Codable` . Making HTTP requests is one of first things to learn when starting iOS and macOS development with Swift 5. In this article we'll build modern networking layer with Swift 5 APIs: URLSession, the Combine framework and Codable. We'll discuss why such libraries as Alamofire, AFNetworking and Moya are overhead. To sharpen our knowledge, we'll query Github REST API, synchronize HTTP requests in

How to handle json reponse in swift 3 | xcode 8, The JSON nests name inside favoriteToy and all the JSON keys are the same as the Employee and Toy stored properties, so you can easily understand the JSON structure based on your data types hierarchy. If your property names match your JSON field names, and your properties are all Codable, then you can convert to or from JSON very easily. You

Comments
  • Well, you've got a JSON object containing other JSON objects. Which means a dictionary containing other dictionaries. Just access them. (Hint: Read the documentation.)
  • Great pattern! Slight change: delegate should be delegate: APIProtocol? so that the callback is optional.
  • @jlhonora Yes! Good call. I think I have actually changed the code in my project to reflect that.
  • This pattern looks great. However, there seems to be a bug in your code listing above. The class ActivityViewController should implement APIProtocol and not APIController.
  • @Shreyas I am glad you like it! And, thanks for pointing out my typo. I've fixed it as you suggested.
  • i tried without the first [0] and then it worked for me.
  • Looks like you keep posting this same answer (a ton of code, no description, nothing) to several questions. Why? If they're the same question, then start flagging duplicates. Not exactly sure what your goal is, by repeatedly posting such lengthy code.
  • but one WebServiceHelper class use for get and post method with image upload method in entire application
  • If this is meant to be an answer (I really cannot tell), then it needs rephrasing, explanation and if possible a touch of readability.