Skip to main content

Nested JSON Parsing with Alamofire and SwiftyJSON in Swift 4

Build A Simple API (Custom JSON) with Alamofire & SwiftyJSON 


This Full Example helps to design a UIViewController WithOut StoryBoard with a UITableViewController, Custom Cell design to show data ion to api service json, this Tutorial  helps to understand how to use Alamofire with SwiftyJSON to hit an API and fetch results, parse them and show the results in an UITableViewController.

A Nested JSON :- like
/*{
"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"
}
}
*/

Web Service api -  https://api.androidhive.info/contacts/ parse the data and show result in tableView.

First create pod file install Alamofire and SwiftyJSON API

Open Terminal -> Then go source folder your create project cd foldername, after type
pod init
open podfile
then edit open podfile
pod 'Alamofile'
pod 'SwiftyJSON'

Then Save podfile and install podfile in terminal - pod install
Then Create a simple Project swift 4 Project Name ContactDetail. Class

AppDelegate.swift - 

Class - 
import UIKit
import Alamofire

@UIApplicationMain
  class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    var demoViewController: DemoViewController?
    var navNavigation: UINavigationController?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow.init(frame: UIScreen.main.bounds)
        demoViewController = DemoViewController(nibName: "DemoViewController", bundle: nil)
        navNavigation = UINavigationController(rootViewController: demoViewController!)
        window?.rootViewController = navNavigation
        window?.makeKeyAndVisible()
        
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

Now Create a Model Class

Model.swift - > 

import Foundation
struct AkhilDemo {
    let name: String!
    let email: String!
    let gender: String!
    let address: String!
    let id: String!
    let phone: Phone

    init(json: [String: Any]) {
        let Name =  json["name"] as? String
        let Email =  json["email"] as? String
        let Gender =  json["gender"] as? String
        let Address =  json["address"] as? String
        let Id =  json["id"] as? String
        let phoneDict = json["phone"] as? [String: Any]
        let phone = Phone(json: phoneDict!)
        
        self.name = Name
        self.email = Email
        self.gender = Gender
        self.address = Address
        self.id = Id
        self.phone = phone
        
        //self.phone = json["phone"] as? [String]
    }
struct Phone {
        let mobile: String!
        let home: String!
        let office: String!
        
        init(json: [String: Any])  
            let Mobile = json["mobile"] as? String
            let Home = json["home"] as? String
            let office = json["office"] as? String
            
            self.home = Home
            self.mobile = Mobile
            self.office = office
            
        }
    }
}

--Edit ViewController Class - ContactDetailViewController.swift
Import Alamofile & SwiftyJSON and design tableView  with Custom Cell - pCell.swift - 


ContactDetailViewController.swift -> 

import UIKit
import Alamofire
import SwiftyJSON
class DemoViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
   
    @IBOutlet var tableView: UITableView!
    var akhildemo: [AkhilDemo] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UINib(nibName: "pCell", bundle: nil), forCellReuseIdentifier: "Cell")
        getJSON()
        // Do any additional setup after loading the view.
    }
    func getJSON(){ Alamofire.request("https://api.androidhive.info/contacts/").responseJSON(completionHandler: {(response) in
        if response.value != nil{
            //print(response)
            if let json = response.result.value as? [String: Any]{
                if let contact = json["contacts"] as? [[String: Any]]{
                    for dic in contact {
                        let contacts = AkhilDemo.init(json: dic)
                        self.akhildemo.append(contacts)
                    }
                    self.tableView.reloadData()
                }
            }
            
        } else{
            print("error")
        }
        
    })
        
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.akhildemo.count
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! pCell
        cell.idLabel.text = self.akhildemo[indexPath.row].id
        cell.nameLabel.text = self.akhildemo[indexPath.row].name
        cell.emailLabel.text = self.akhildemo[indexPath.row].email
        cell.adressLabel.text = self.akhildemo[indexPath.row].address
        cell.ageLabel.text = self.akhildemo[indexPath.row].gender
        cell.phoneLabel.text = self.akhildemo[indexPath.row].phone.mobile
        
        return cell
    }

}


Custom Cell - pCell.swift - 


import UIKit

class pCell: UITableViewCell {
    
    @IBOutlet var idLabel: UILabel!
    @IBOutlet var nameLabel: UILabel!
    @IBOutlet var emailLabel: UILabel!
    @IBOutlet var ageLabel: UILabel!
    @IBOutlet var adressLabel: UILabel!
    @IBOutlet var phoneLabel: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
   override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}


Output- 









Comments

Popular posts from this blog

Add a Scene Delegate to your existing project with Storyboard in Swift

To add a scene delegate, first, create a new Swift file that you’ll call "SceneDelegate" containing a subclass of UIResponder, just like the AppDelegate, and that conforms to UIWindowSceneDelegate.  As your app might supports other versions than iOS 13, make this class only available for iOS 13. This is what you should have : If you are working a project that is storyboard based, please set storyboard  initial view controller SceneDelegate.swift import UIKit @available ( iOS 13.0 , *) class SceneDelegate : UIResponder , UIWindowSceneDelegate {     var window : UIWindow ?     func scene ( _ scene: UIScene , willConnectTo session: UISceneSession , options connectionOptions: UIScene . ConnectionOptions ) {                  let storyboard = UIStoryboard (name: "Main" , bundle: nil )         let initialViewController = storyboard. instantiateViewController (withIdentifier: "ViewController" )         let mainNavigationController = UINavigationControlle

How Create Animated Circle Progress Bar iOS 11 Swift 4

  Animated Circle Progress Bar iOS 11 Swift 4 With MBCircularProgressBa r - https://github.com/MatiBot/MBCircularProgressBar A circular, animatable & highly customizable progress bar from the Interface Builder Swift, Using pod fite MBCircularProgressBar Installation Cocoapods terminal. pod "MBCircularProgressBar" That - A Simple Steps to installed pod file -        Open terminal        Command on terminal go to project folder Cd path        set your project path on terminal.        command : pod init        open pod file - open -e podfile        added in pod file with in : pod "MBCircularProgressBar"        Command : Pod install        Close project of Xcode        open your Project from terminals        Command : open PodDemos.xcworkspace After opern StoryBoard and Now drag a UIView over the viewController in storyboard Or set UIView Constraint width, height or verticle or horzentail space and set a class MBCircul

How to Use Multiple Sections in UITableView iOS Swift !

Multiple sections in UITableView iOS Swift. UITableView is very important part of iOS ecosystem. So we split tableviews in sections. Then its easier to find right information.  1. First let’s create a project as usual. Create a new single view application X code project. Set project name to UIViewController.  2. Go to main storyboard & select view controller & use UITableView 3. Select tableview & make it initial view controller  4 Create a custom Sections Class like Name => TableSections, create register cell static return “ getCellNibs ” method. Then create  4 section enum “TableItems” then after append all sections to an array model. import UIKit struct CellNib {      static func getCellNibs () -> [ String ] {          return [ "Cell1" , "Cell2" , "Cell3" , "Cell4" ]     } } enum TableItems : Int {      case TableSections1      case TableSections2      case TableSections3      case TableSections4 } class TableSec