Skip to main content

Parsing JSON data from Alamofire into Response Array or Dictionary

1. model class used


struct REVIEWLIST {
    
    let rating_id: String!
    let user_id: String!
    let user_name: String!
    let user_email: String!
    let rating_type: String!
    let rating: String!
    let fac_id: String!
    let event_id: String!
    let admin_approval: String!
    let report_abuse: String!
    let created_on : String!
    let updated_on: String!
    let updated_by: String!
    let review_message: String!
    
    let review_listing: [ReviewListing]
    
    init(json: [String: Any]) {
        
        let rating_id =  json["rating_id"] as? String
        let user_id =  json["user_id"] as? String
        let user_name =  json["user_name"] as? String
        let user_email =  json["user_email"] as? String
        let rating_type =  json["rating_type"] as? String
        let rating =  json["rating"] as? String
        let fac_id =  json["fac_id"] as? String
        let event_id =  json["event_id"] as? String
        let admin_approval =  json["admin_approval"] as? String
        let report_abuse =  json["report_abuse"] as? String
        let created_on =  json["created_on"] as? String
        let updated_on =  json["updated_on"] as? String
        let updated_by =  json["updated_by"] as? String
        let review_message =  json["review_message"] as? String

        let review_listingArray = json["review_listing"] as? [[String: Any]]
        self.review_listing = parseReviewListingListArray(from: review_listingArray)
        
        self.rating_id = rating_id
        self.user_id = user_id
        self.user_name = user_name
        self.user_email = user_email
        self.rating_type = rating_type
        self.rating = rating
        self.fac_id = fac_id
        self.event_id = event_id
        self.admin_approval = admin_approval
        self.report_abuse = report_abuse
        self.created_on = created_on
        self.updated_on = updated_on
        self.updated_by = updated_by
        self.review_message = review_message

    }
    
}

struct ReviewListing {
    
    let review_id: String!
    let rating_id: String!
    let review_message: String!
    
    
    init(json: [String: Any]) {
    
    let review_id =  json["review_id"] as? String
    let rating_id =  json["rating_id"] as? String
    let review_message =  json["review_message"] as? String
    
        
             self.review_id = review_id
             self.rating_id = rating_id
             self.review_message = review_message
             
         }
}

private func parseReviewListingListArray(from json: [[String: Any]]?) -> [ReviewListing] {
    guard let ReveiwArray = json else { return []}
    var arrayTemp = [ReviewListing]()
    for (_, dict) in ReveiwArray.enumerated() {
        let RArray = ReviewListing(json: dict)
        arrayTemp.append(RArray)
    }
    return arrayTemp
}


2. methods


import Foundation
import Alamofire
class HTTPClient: NSObject
{
    let commonFunctionFileObj = CommonFunction()
    var activityIndicatorContainerView = UIView()
    var activityIndicator = UIActivityIndicatorView()
    
    func postRequest(url:String, params:[String: String], headers:HTTPHeaders?,view: UIView ,completion:@escaping (_ responseData:Result<Any>?, _ error:Error?)->Void)
    {
        let activityIndicatorObject = commonFunctionFileObj.createActivityIndicatorInAllViewController(view: view)
        activityIndicator = activityIndicatorObject.1
        activityIndicatorContainerView = activityIndicatorObject.0
        
        commonFunctionFileObj.activityIndicatorShowAndStartAnimating(activityIndicator: activityIndicator, activityIndicatorContainerView: activityIndicatorContainerView)
        
        Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding(), headers: headers).responseJSON
            {
                response in
                
                print("response.result \(response.result.value)")
                guard response.result.isSuccess,
                    (response.result.value != nil) else {
                        debugPrint("Error while fetching data: \(String(describing: response.result.error))")
                        self.commonFunctionFileObj.activityIndicatorHideAndStopAnimating(activityIndicator: self.activityIndicator, activityIndicatorContainerView: self.activityIndicatorContainerView)
                        
                        completion(nil,response.result.error)
                        
                        return
                }
                
                self.commonFunctionFileObj.activityIndicatorHideAndStopAnimating(activityIndicator: self.activityIndicator, activityIndicatorContainerView: self.activityIndicatorContainerView)
                
                completion(response.result,nil)
                
        }
    }
    
    func getRequest(url:String, params:[String: Any]?,headers:HTTPHeaders?,completion:@escaping (_ responseData:Result<Any>?, _ error:Error?)->Void)
    {
        
        //        Alamofire.SessionManager.default.session.configuration.timeoutIntervalForRequest = 5
        //        Alamofire.SessionManager.default.session.configuration.timeoutIntervalForRequest = 5
        
        print("getRequestgetRequest")
        Alamofire.request(url, method: .get, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (responseData: DataResponse<Any>)  in
            
            print("Request: \(String(describing: responseData.result.value))")   // original url request
            print("Response: \(String(describing: responseData.response))") // http url response
            print("Result: \(responseData.result)")
            
            
            
            // response serialization result
            switch (responseData.result)
            {
            case .success(_):
                
                if let response = responseData.result.value{
                    
                    print("JSON: \(response)") // serialized json response
                    
                    // completionBlock(responseData.result.value as? [String : Any] ,(responseData.response?.statusCode) ?? 0,responseData.result.error)
                }
                else
                {
                    // completionBlock(responseData.result.value as? [String : Any] ,(responseData.response?.statusCode) ?? 0,responseData.result.error)
                    
                }
                break
            case .failure(_):
                if (responseData.result.value == nil) {
                    if responseData.response?.statusCode == 500 {
                        // completionBlock(nil ,(responseData.response?.statusCode) ?? 0,"Unable to connect to server. Please try again after sometime." as? Error)
                        
                    }
                    else
                    {
                        // completionBlock(nil ,(responseData.response?.statusCode) ?? 0,responseData.result.error)
                    }
                }
                else{
                    //completionBlock(responseData.result.value as? [String : Any] ,(responseData.response?.statusCode) ?? 0,responseData.result.error)
                }
                
                break
            }
            
            
        }
        
    }
    
}


3. call json

    func Api(){
       
        let id = preferences.value(forKey: id)
        print(id!)
       
        if id != nil {
            let parameter: [String: AnyObject] = [
               
                "id": id as AnyObject
            ]
           
            DispatchQueue.main.async {
               
                self.httpClient.postRequest(url: url, params: parameter as! [String : String], headers: nil, view: self.view) { (result, error) in
               
                print("LISTING---\(String(describing: result?.value))")
               
                if result?.value as? NSDictionary != nil {
                    let resultDic = result?.value as! NSDictionary
                    let status  = String(describing: resultDic.value(forKey: "status")!)
                    let message = String(describing: resultDic.value(forKey: "response_messege"))
                   
                    if status != "0" {
                       
                        if let json = resultDic.value(forKey: "response") as? NSDictionary {
                            print(json)
                           
                            if let dashbord_booking_Dict = json.value(forKey: "dashbord_booking") as? NSDictionary {
                                print(dashbord_booking_Dict)
                               
                            let totalBooking = String(describing: dashbord_booking_Dict.value(forKey: "total_booking_count")!)
                                print(totalBooking)
                            preferences.set(totalBooking, forKey: Total_Booking_Count)
                                                                                         
                            let totalConfirmBooking = String(describing: dashbord_booking_Dict.value(forKey: "total_confirmed_booking_count")!)
                                preferences.set(totalConfirmBooking, forKey: Total_Confirmed_Booking_Count)
                               
                               
                                if let totalList = dashbord_booking_Dict as? [String: Any]{
                                        print("--------Total List -----\(totalList)")
                                        let dashbordbookingList = Dashbord_Booking.init(json: totalList)
                                        self.dashbordbooking.append(dashbordbookingList)
                                }
                            }
                           
                            if let review_summary_Dict = json.value(forKey: "review_summary") as? NSDictionary{
                                print(review_summary_Dict)
                               
                            let total_1_review = String(describing: review_summary_Dict.value(forKey: "total_1_review")!)
                                print(total_1_review)
                                preferences.set(total_1_review, forKey: TotalReview1)
                                                         
                            let total_2_review = String(describing: review_summary_Dict.value(forKey: "total_2_review")!)
                                preferences.set(total_2_review, forKey: TotalReview2)
                            let total_3_review = String(describing: review_summary_Dict.value(forKey: "total_3_review")!)
                                preferences.set(total_3_review, forKey: TotalReview3)
                            let total_4_review = String(describing: review_summary_Dict.value(forKey: "total_4_review")!)
                                preferences.set(total_4_review, forKey: TotalReview4)
                            let total_5_review = String(describing: review_summary_Dict.value(forKey: "total_5_review")!)
                            preferences.set(total_5_review, forKey: TotalReview5)
                               
                                let review_count = String(describing: review_summary_Dict.value(forKey: "review_count")!)
                                print(review_count)
                                preferences.set(review_count, forKey: ReviewCount)
                               
                                if let totalList = review_summary_Dict as? [String: Any]{
                                    print("--------Total List -----\(totalList)")
                                    let reviewList = Total_Review_Listing.init(json: totalList)
                                    self.totalReviewListing.append(reviewList)
                                }
                               
                            }
                           
                            if let upcomingEventsArray = json.value(forKey: "upcoming_events") as? NSArray{
                                print(upcomingEventsArray)
               
                                if let totalList = upcomingEventsArray as? [[String: Any]]{
                                   
                                    for dic in totalList {
                                        let events = UpcomingEvents.init(json: dic)
                                        self.upcoming_Events.append(events)
                                    }
                                   
                                }
                            }
                            self.mainDashboardTableView.reloadData()
                        }
                       
                    }else{
                        self.commonFunction.showAlert(message: message, view: self)
                    }
                }
                if error?._code == -1009 || error?._code == -4
                {
                    self.commonFunction.showAlert(message: error!.localizedDescription , view: self)
                }
            }
        }
        }
    }

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