Handling JSON with Alamofire & SwiftyJSON and Adding to UITableView in Swift












1














I want to use Alamofire and SwiftyJSON for my REST API. I have accessed the root JSON but I can't access the objects of JSON.



This my json result:



[
{
"ID": 1,
"name": "JABODETABEK",
"cabang": [
{
"ID": 1,
"wilayah_id": 1,
"name": "Jembatan Lima"
},
{
"ID": 2,
"wilayah_id": 1,
"name": "Kebon Jeruk"
}
]
},
{
"ID": 2,
"name": "Sumatra Selatan dan Bangka Belitung",
"cabang": [
{
"ID": 6,
"wilayah_id": 2,
"name": "A. Yani - Palembang"
},
{
"ID": 7,
"wilayah_id": 2,
"name": "Veteran - Palembang"
}
]
}
}


With this code:



Alamofire.request(url).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)

if let resData = swiftyJsonVar.arrayObject {
self.productArray = resData as! [[String:AnyObject]]
print("MyArray: (self.productArray)")
}
}
}


My tableview:



func numberOfSections(in tableView: UITableView) -> Int {
return self.productArray.count
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let dic = productArray[section]
return dic["name"] as? String
}

func tableView(_ tableView: UITableView, numberOfRowsInSection sectionInd: Int) -> Int {
return (((?)))
}


Please help me in viewing the datas in my tableView cells using Alamofire and SwiftyJSON. How can I access that data? I mean how can I get numberOfRowsInSection?










share|improve this question
























  • productArray[section]["cabang"].count
    – Himanshu Moradiya
    Nov 12 at 4:54










  • Where do you reload your table view? Is reload called in main thread?
    – Timur Bernikowich
    Dec 18 at 10:29
















1














I want to use Alamofire and SwiftyJSON for my REST API. I have accessed the root JSON but I can't access the objects of JSON.



This my json result:



[
{
"ID": 1,
"name": "JABODETABEK",
"cabang": [
{
"ID": 1,
"wilayah_id": 1,
"name": "Jembatan Lima"
},
{
"ID": 2,
"wilayah_id": 1,
"name": "Kebon Jeruk"
}
]
},
{
"ID": 2,
"name": "Sumatra Selatan dan Bangka Belitung",
"cabang": [
{
"ID": 6,
"wilayah_id": 2,
"name": "A. Yani - Palembang"
},
{
"ID": 7,
"wilayah_id": 2,
"name": "Veteran - Palembang"
}
]
}
}


With this code:



Alamofire.request(url).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)

if let resData = swiftyJsonVar.arrayObject {
self.productArray = resData as! [[String:AnyObject]]
print("MyArray: (self.productArray)")
}
}
}


My tableview:



func numberOfSections(in tableView: UITableView) -> Int {
return self.productArray.count
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let dic = productArray[section]
return dic["name"] as? String
}

func tableView(_ tableView: UITableView, numberOfRowsInSection sectionInd: Int) -> Int {
return (((?)))
}


Please help me in viewing the datas in my tableView cells using Alamofire and SwiftyJSON. How can I access that data? I mean how can I get numberOfRowsInSection?










share|improve this question
























  • productArray[section]["cabang"].count
    – Himanshu Moradiya
    Nov 12 at 4:54










  • Where do you reload your table view? Is reload called in main thread?
    – Timur Bernikowich
    Dec 18 at 10:29














1












1








1







I want to use Alamofire and SwiftyJSON for my REST API. I have accessed the root JSON but I can't access the objects of JSON.



This my json result:



[
{
"ID": 1,
"name": "JABODETABEK",
"cabang": [
{
"ID": 1,
"wilayah_id": 1,
"name": "Jembatan Lima"
},
{
"ID": 2,
"wilayah_id": 1,
"name": "Kebon Jeruk"
}
]
},
{
"ID": 2,
"name": "Sumatra Selatan dan Bangka Belitung",
"cabang": [
{
"ID": 6,
"wilayah_id": 2,
"name": "A. Yani - Palembang"
},
{
"ID": 7,
"wilayah_id": 2,
"name": "Veteran - Palembang"
}
]
}
}


With this code:



Alamofire.request(url).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)

if let resData = swiftyJsonVar.arrayObject {
self.productArray = resData as! [[String:AnyObject]]
print("MyArray: (self.productArray)")
}
}
}


My tableview:



func numberOfSections(in tableView: UITableView) -> Int {
return self.productArray.count
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let dic = productArray[section]
return dic["name"] as? String
}

func tableView(_ tableView: UITableView, numberOfRowsInSection sectionInd: Int) -> Int {
return (((?)))
}


Please help me in viewing the datas in my tableView cells using Alamofire and SwiftyJSON. How can I access that data? I mean how can I get numberOfRowsInSection?










share|improve this question















I want to use Alamofire and SwiftyJSON for my REST API. I have accessed the root JSON but I can't access the objects of JSON.



This my json result:



[
{
"ID": 1,
"name": "JABODETABEK",
"cabang": [
{
"ID": 1,
"wilayah_id": 1,
"name": "Jembatan Lima"
},
{
"ID": 2,
"wilayah_id": 1,
"name": "Kebon Jeruk"
}
]
},
{
"ID": 2,
"name": "Sumatra Selatan dan Bangka Belitung",
"cabang": [
{
"ID": 6,
"wilayah_id": 2,
"name": "A. Yani - Palembang"
},
{
"ID": 7,
"wilayah_id": 2,
"name": "Veteran - Palembang"
}
]
}
}


With this code:



Alamofire.request(url).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)

if let resData = swiftyJsonVar.arrayObject {
self.productArray = resData as! [[String:AnyObject]]
print("MyArray: (self.productArray)")
}
}
}


My tableview:



func numberOfSections(in tableView: UITableView) -> Int {
return self.productArray.count
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let dic = productArray[section]
return dic["name"] as? String
}

func tableView(_ tableView: UITableView, numberOfRowsInSection sectionInd: Int) -> Int {
return (((?)))
}


Please help me in viewing the datas in my tableView cells using Alamofire and SwiftyJSON. How can I access that data? I mean how can I get numberOfRowsInSection?







ios json swift uitableview swifty-json






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 at 5:11









rmaddy

238k27309375




238k27309375










asked Nov 12 at 4:45









Irwan Madness

180210




180210












  • productArray[section]["cabang"].count
    – Himanshu Moradiya
    Nov 12 at 4:54










  • Where do you reload your table view? Is reload called in main thread?
    – Timur Bernikowich
    Dec 18 at 10:29


















  • productArray[section]["cabang"].count
    – Himanshu Moradiya
    Nov 12 at 4:54










  • Where do you reload your table view? Is reload called in main thread?
    – Timur Bernikowich
    Dec 18 at 10:29
















productArray[section]["cabang"].count
– Himanshu Moradiya
Nov 12 at 4:54




productArray[section]["cabang"].count
– Himanshu Moradiya
Nov 12 at 4:54












Where do you reload your table view? Is reload called in main thread?
– Timur Bernikowich
Dec 18 at 10:29




Where do you reload your table view? Is reload called in main thread?
– Timur Bernikowich
Dec 18 at 10:29












3 Answers
3






active

oldest

votes


















1





+50









Try this:



Alamofire.request("url").responseJSON { (responseData) -> Void in
if let data = response.data {
guard let json = try? JSON(data: data) else { return }
self.productArray = json.arrayValue //productArray type must be [[String:AnyObject]]
}


after that update tableView delegate functions:



func numberOfSections(in tableView: UITableView) -> Int {
return self.productArray.count
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let dic = productArray[section]
return dic["name"].string
}

func tableView(_ tableView: UITableView, numberOfRowsInSection sectionInd: Int) -> Int {
return productArray[sectionInd]["cabang"].arrayValue.count
}





share|improve this answer































    0














    First thing is don't use Dictionary or array of Dictionary now. You can use Codable instead https://medium.com/@multidots/essentials-of-codable-protocol-in-swift-4-c795a645c3e1,



    if you are using dictionary then use Any instead of AnyObject.



    Your answer is (self.productArray[sectionInd]["cabang"] as! [[String:Any]]).count



    func tableView(_ tableView: UITableView, numberOfRowsInSection sectionInd: Int) -> Int {

    return ((self.productArray[sectionInd]["cabang"] as! [[String:Any]]).count
    }





    share|improve this answer





























      -2














      //MARK:- UITableView Delegate & DataSource



      func numberOfSections(in tableView: UITableView) -> Int {

      return self.productArray.count
      }

      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

      let dictionaryProduct = self.productArray.object(at: section) as! NSDictionary
      let arrayCabang = dictionaryProduct.object(forKey: "cabang") as! NSArray
      if arrayCabang.count > 0 {

      return arrayCabang.count
      } else {

      return 0
      }
      }

      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


      let dictionaryProduct = self.productArray.object(at: indexPath.section) as! NSDictionary
      let arrayCabang = dictionaryProduct.object(forKey: "cabang") as! NSArray
      if arrayCabang.count > 0 {

      let dictionaryCurrentCabang = arrayCabang.object(at: indexPath.row) as! NSDictionary

      //Here you get data of cabangs at the particular index
      }

      return cell!
      }





      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53256086%2fhandling-json-with-alamofire-swiftyjson-and-adding-to-uitableview-in-swift%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1





        +50









        Try this:



        Alamofire.request("url").responseJSON { (responseData) -> Void in
        if let data = response.data {
        guard let json = try? JSON(data: data) else { return }
        self.productArray = json.arrayValue //productArray type must be [[String:AnyObject]]
        }


        after that update tableView delegate functions:



        func numberOfSections(in tableView: UITableView) -> Int {
        return self.productArray.count
        }

        func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let dic = productArray[section]
        return dic["name"].string
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection sectionInd: Int) -> Int {
        return productArray[sectionInd]["cabang"].arrayValue.count
        }





        share|improve this answer




























          1





          +50









          Try this:



          Alamofire.request("url").responseJSON { (responseData) -> Void in
          if let data = response.data {
          guard let json = try? JSON(data: data) else { return }
          self.productArray = json.arrayValue //productArray type must be [[String:AnyObject]]
          }


          after that update tableView delegate functions:



          func numberOfSections(in tableView: UITableView) -> Int {
          return self.productArray.count
          }

          func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
          let dic = productArray[section]
          return dic["name"].string
          }

          func tableView(_ tableView: UITableView, numberOfRowsInSection sectionInd: Int) -> Int {
          return productArray[sectionInd]["cabang"].arrayValue.count
          }





          share|improve this answer


























            1





            +50







            1





            +50



            1




            +50




            Try this:



            Alamofire.request("url").responseJSON { (responseData) -> Void in
            if let data = response.data {
            guard let json = try? JSON(data: data) else { return }
            self.productArray = json.arrayValue //productArray type must be [[String:AnyObject]]
            }


            after that update tableView delegate functions:



            func numberOfSections(in tableView: UITableView) -> Int {
            return self.productArray.count
            }

            func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
            let dic = productArray[section]
            return dic["name"].string
            }

            func tableView(_ tableView: UITableView, numberOfRowsInSection sectionInd: Int) -> Int {
            return productArray[sectionInd]["cabang"].arrayValue.count
            }





            share|improve this answer














            Try this:



            Alamofire.request("url").responseJSON { (responseData) -> Void in
            if let data = response.data {
            guard let json = try? JSON(data: data) else { return }
            self.productArray = json.arrayValue //productArray type must be [[String:AnyObject]]
            }


            after that update tableView delegate functions:



            func numberOfSections(in tableView: UITableView) -> Int {
            return self.productArray.count
            }

            func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
            let dic = productArray[section]
            return dic["name"].string
            }

            func tableView(_ tableView: UITableView, numberOfRowsInSection sectionInd: Int) -> Int {
            return productArray[sectionInd]["cabang"].arrayValue.count
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 12 at 5:16









            Kuldeep

            2,47641534




            2,47641534










            answered Nov 12 at 5:12









            andesta.erfan

            449121




            449121

























                0














                First thing is don't use Dictionary or array of Dictionary now. You can use Codable instead https://medium.com/@multidots/essentials-of-codable-protocol-in-swift-4-c795a645c3e1,



                if you are using dictionary then use Any instead of AnyObject.



                Your answer is (self.productArray[sectionInd]["cabang"] as! [[String:Any]]).count



                func tableView(_ tableView: UITableView, numberOfRowsInSection sectionInd: Int) -> Int {

                return ((self.productArray[sectionInd]["cabang"] as! [[String:Any]]).count
                }





                share|improve this answer


























                  0














                  First thing is don't use Dictionary or array of Dictionary now. You can use Codable instead https://medium.com/@multidots/essentials-of-codable-protocol-in-swift-4-c795a645c3e1,



                  if you are using dictionary then use Any instead of AnyObject.



                  Your answer is (self.productArray[sectionInd]["cabang"] as! [[String:Any]]).count



                  func tableView(_ tableView: UITableView, numberOfRowsInSection sectionInd: Int) -> Int {

                  return ((self.productArray[sectionInd]["cabang"] as! [[String:Any]]).count
                  }





                  share|improve this answer
























                    0












                    0








                    0






                    First thing is don't use Dictionary or array of Dictionary now. You can use Codable instead https://medium.com/@multidots/essentials-of-codable-protocol-in-swift-4-c795a645c3e1,



                    if you are using dictionary then use Any instead of AnyObject.



                    Your answer is (self.productArray[sectionInd]["cabang"] as! [[String:Any]]).count



                    func tableView(_ tableView: UITableView, numberOfRowsInSection sectionInd: Int) -> Int {

                    return ((self.productArray[sectionInd]["cabang"] as! [[String:Any]]).count
                    }





                    share|improve this answer












                    First thing is don't use Dictionary or array of Dictionary now. You can use Codable instead https://medium.com/@multidots/essentials-of-codable-protocol-in-swift-4-c795a645c3e1,



                    if you are using dictionary then use Any instead of AnyObject.



                    Your answer is (self.productArray[sectionInd]["cabang"] as! [[String:Any]]).count



                    func tableView(_ tableView: UITableView, numberOfRowsInSection sectionInd: Int) -> Int {

                    return ((self.productArray[sectionInd]["cabang"] as! [[String:Any]]).count
                    }






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 12 at 4:53









                    Prashant Tukadiya

                    7,03621846




                    7,03621846























                        -2














                        //MARK:- UITableView Delegate & DataSource



                        func numberOfSections(in tableView: UITableView) -> Int {

                        return self.productArray.count
                        }

                        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

                        let dictionaryProduct = self.productArray.object(at: section) as! NSDictionary
                        let arrayCabang = dictionaryProduct.object(forKey: "cabang") as! NSArray
                        if arrayCabang.count > 0 {

                        return arrayCabang.count
                        } else {

                        return 0
                        }
                        }

                        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


                        let dictionaryProduct = self.productArray.object(at: indexPath.section) as! NSDictionary
                        let arrayCabang = dictionaryProduct.object(forKey: "cabang") as! NSArray
                        if arrayCabang.count > 0 {

                        let dictionaryCurrentCabang = arrayCabang.object(at: indexPath.row) as! NSDictionary

                        //Here you get data of cabangs at the particular index
                        }

                        return cell!
                        }





                        share|improve this answer




























                          -2














                          //MARK:- UITableView Delegate & DataSource



                          func numberOfSections(in tableView: UITableView) -> Int {

                          return self.productArray.count
                          }

                          func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

                          let dictionaryProduct = self.productArray.object(at: section) as! NSDictionary
                          let arrayCabang = dictionaryProduct.object(forKey: "cabang") as! NSArray
                          if arrayCabang.count > 0 {

                          return arrayCabang.count
                          } else {

                          return 0
                          }
                          }

                          func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


                          let dictionaryProduct = self.productArray.object(at: indexPath.section) as! NSDictionary
                          let arrayCabang = dictionaryProduct.object(forKey: "cabang") as! NSArray
                          if arrayCabang.count > 0 {

                          let dictionaryCurrentCabang = arrayCabang.object(at: indexPath.row) as! NSDictionary

                          //Here you get data of cabangs at the particular index
                          }

                          return cell!
                          }





                          share|improve this answer


























                            -2












                            -2








                            -2






                            //MARK:- UITableView Delegate & DataSource



                            func numberOfSections(in tableView: UITableView) -> Int {

                            return self.productArray.count
                            }

                            func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

                            let dictionaryProduct = self.productArray.object(at: section) as! NSDictionary
                            let arrayCabang = dictionaryProduct.object(forKey: "cabang") as! NSArray
                            if arrayCabang.count > 0 {

                            return arrayCabang.count
                            } else {

                            return 0
                            }
                            }

                            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


                            let dictionaryProduct = self.productArray.object(at: indexPath.section) as! NSDictionary
                            let arrayCabang = dictionaryProduct.object(forKey: "cabang") as! NSArray
                            if arrayCabang.count > 0 {

                            let dictionaryCurrentCabang = arrayCabang.object(at: indexPath.row) as! NSDictionary

                            //Here you get data of cabangs at the particular index
                            }

                            return cell!
                            }





                            share|improve this answer














                            //MARK:- UITableView Delegate & DataSource



                            func numberOfSections(in tableView: UITableView) -> Int {

                            return self.productArray.count
                            }

                            func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

                            let dictionaryProduct = self.productArray.object(at: section) as! NSDictionary
                            let arrayCabang = dictionaryProduct.object(forKey: "cabang") as! NSArray
                            if arrayCabang.count > 0 {

                            return arrayCabang.count
                            } else {

                            return 0
                            }
                            }

                            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


                            let dictionaryProduct = self.productArray.object(at: indexPath.section) as! NSDictionary
                            let arrayCabang = dictionaryProduct.object(forKey: "cabang") as! NSArray
                            if arrayCabang.count > 0 {

                            let dictionaryCurrentCabang = arrayCabang.object(at: indexPath.row) as! NSDictionary

                            //Here you get data of cabangs at the particular index
                            }

                            return cell!
                            }






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 12 at 6:19

























                            answered Nov 12 at 5:25









                            Rohit Parihar

                            4617




                            4617






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53256086%2fhandling-json-with-alamofire-swiftyjson-and-adding-to-uitableview-in-swift%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Florida Star v. B. J. F.

                                Danny Elfman

                                Lugert, Oklahoma