简体   繁体   中英

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

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 ?

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
}

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
}

//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!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM