Swift 3 / Alamofire: Cant load the table with the data

僤鯓⒐⒋嵵緔 提交于 2019-12-14 03:49:13

问题


I am trying to load the data on the UItableview, I am able to see the records fetched in the output panel but not able to fetch them on the UItableview.

Please find the code below:

import UIKit
import Alamofire
import SwiftyJSON


class CategoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSURLConnectionDelegate {

var tableData = Array<Category>()
var arrRes = [[String:AnyObject]]() //Array of dictionary
var category = [Category]()
var catTitle = ""
var id = ""



@IBOutlet weak var catTitleRec: UILabel!

@IBOutlet weak var tableview: UITableView!




override func viewDidLoad() {
    super.viewDidLoad()

    catTitleRec.text = catTitle
    loadCategories(id:id)
}

func loadCategories(id : String) {


    let userDic : [String : AnyObject] = ["id":id as AnyObject]

    Alamofire.upload(multipartFormData: { multipartFormData in

        for (key, value) in userDic {
            multipartFormData.append(value.data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }

    },to: "http://www.URL.com.au/database/results.php" , method: .post, headers: nil ,
      encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.response { [weak self] response in
                guard self != nil else {
                    return
                }
                debugPrint(response)

            }

            upload.responseJSON {  response in

                print(response)
            //    let responseJSON = response.result.value as! NSDictionary


              //  print(responseJSON)



            }

        case .failure(let encodingError):
            print("error:\(encodingError)")
        }


    })
    tableview.reloadData()
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    tableview.reloadData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //return myarray.count
    return arrRes.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell") as! CategoryCellTableViewCell
    var dict = arrRes[indexPath.row]

    cell.catName.text = dict["category.NAME"] as? String
    cell.total?.text = dict["TOTAL"] as? String


    return cell
}

}

and my CategoryCellTableViewCell.swift code:

import UIKit

class CategoryCellTableViewCell: UITableViewCell {

@IBOutlet weak var catName: UILabel!

@IBOutlet weak var total: 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
}

}

I tried to seek some help online but couldnt get but thanks a lot for the time :)

dict output:

SUCCESS: (
    {
    NAME = "COSMETIC PRODUCTS & SERVICES";
    TOTAL = 1;
    id = 54300;
},
    {
    NAME = TATTOOING;
    TOTAL = 1;
    id = 225700;
}

)


回答1:


Try this I think you forget the filling array and also set the datasource,and delegate of UITableView

import UIKit
import Alamofire
import SwiftyJSON


class CategoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSURLConnectionDelegate {

    var tableData = Array<Category>()
    var category = [Category]()
    var arrRes = [NSDictionary]()
    var catTitle = ""
    var id = ""



    @IBOutlet weak var catTitleRec: UILabel!

    @IBOutlet weak var tableview: UITableView!




    override func viewDidLoad() {
        super.viewDidLoad()

        catTitleRec.text = catTitle
        loadCategories(id:id)
    }

    func loadCategories(id : String) {


        let userDic : [String : AnyObject] = ["id":id as AnyObject]

        Alamofire.upload(multipartFormData: { multipartFormData in

            for (key, value) in userDic {
                multipartFormData.append(value.data(using: String.Encoding.utf8.rawValue)!, withName: key)
            }

        },to: "URL" , method: .post, headers: nil ,
          encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.response { [weak self] response in
                    guard self != nil else {
                        return
                    }
                    debugPrint(response)
                }
                upload.responseJSON { response in
                    print(response)

                    self.arrRes = response.result.value as? NSArray as! [NSDictionary]
                    DispatchQueue.main.async {
                        self.tableview.reloadData()
                    }
                }

            case .failure(let encodingError):
                print("error:\(encodingError)")
            }


        })
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        tableview.reloadData()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //return myarray.count
        return arrRes.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
        let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell") as! CategoryCellTableViewCell 
        var dict = arrRes[indexPath.row]
        cell.catName.text = dict["NAME"] as? String
        cell.total?.text = dict["TOTAL"] as? String 


        return cell 
    } 



}



回答2:


Try this.

case .success(let upload, _, _):
                upload.response { [weak self] response in
                    guard self != nil else {
                        return
                    }
                    debugPrint(response)
                }
                upload.responseJSON {  response in
                    print(response)
                //    let responseJSON = response.result.value as! NSDictionary
                  //  print(responseJSON)
                 DispatchQueue.main.async {
                   self.tableview.reloadData()
                  }
                }



回答3:


This asynchronous calling of method so you need do reload data inside the block as below :

switch encodingResult {
        case .success(let upload, _, _):
            upload.response { [weak self] response in
                guard self != nil else {
                    return
                }
                debugPrint(response)

            }
            upload.responseJSON {  response in
                print(response)
            //    let responseJSON = response.result.value as! NSDictionary
             arrRes = responseJSON // you need to assign data here
             tableview.reloadData()
              //  print(responseJSON)

            }

        case .failure(let encodingError):
            print("error:\(encodingError)")
        }



回答4:


you are getting multiple values of name in JSON it is array of Dictionaries you need to get the name stored in dictionary its not directly in array output get it like below

for dict in dataDict {
      let userName = dict["NAME"] as? String
      let userTotal = dict["TOTAL"] as? String
      // Store data in User Default // Not required
      UserDefaults.standard.set(userName, forKey:"username")
      UserDefaults.standard.set(userTotal, forKey:"totalNumber")
}

or add it in array and in cellforRow use the array to show the details



来源:https://stackoverflow.com/questions/44838857/swift-3-alamofire-cant-load-the-table-with-the-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!