Skip to main content

Custom Loader (Activity Indicator) in Swift

Creating a custom activity indicator in Swift allows you to tailor the appearance and behavior of your loading spinner to fit the style of your app. Here's a step-by-step guide to creating a simple custom activity indicator using UIView Step 1: Create a New Swift File for the Custom Activity Indicator Create a new Swift file and name it  RotatingCirclesView.swift . Add the following code to define a custom UIView subclass for your activity indicator: // //   RotatingCirclesView.swift //   Welcome In // //   Created by Praveen Kumar on 05/09/24. // import UIKit class RotatingCirclesView : UIView {          let circle1 = UIView ( frame : CGRect ( x : 20 , y : 20 , width : 60 , height : 60 ))     let circle2 = UIView ( frame : CGRect ( x : 120 , y : 20 , width : 60 , height : 60 ))          let position : [ CGRect ] = [ CGRect ( x : 30 , y : 20 , width : 60 , height : 60 ), CGRect ( x : 60 , y : 15 ,...

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