我对快速处理请求和响应还很陌生。这是我坚持的代码。我从dataArray的Web服务获取值,但未在tableview中加载。请有人帮忙。

import UIKit
import Foundation
import Alamofire
import SwiftyJSON

class AddOnsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    var dataArray = [AnyObject]()
    var addOnsURL = "http://econstrademosite.com/food_delivery/?****************"

    override func viewDidLoad() {
        super.viewDidLoad()
        self.automaticallyAdjustsScrollViewInsets = false
        self.tableView.reloadData()
        callData()
    }

    @IBAction func goBackToHome(sender: UIBarButtonItem){

        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "base") as! SWRevealViewController
        self.present(vc, animated: true, completion: nil)
    }

    func callData(){

        Alamofire.request(addOnsURL).responseJSON { response in

            let result = response.result
            if let dict = result.value as? Dictionary<String, AnyObject>{
                if let innerDict = dict["data"]?["result"]{
                    self.dataArray = innerDict as! [AnyObject]
                    print(self.dataArray)
                }
            }
        }
    }

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print(dataArray.count)
        return dataArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! exampleTableViewCell
        let itemName = dataArray[indexPath.row]["item_name"]
        cell.label.text! = itemName as! String

        return cell
    }

}

最佳答案

    func callData(){

        Alamofire.request(addOnsURL).responseJSON { response in

            let result = response.result
            if let dict = result.value as? Dictionary<String, AnyObject>{
                if let innerDict = dict["data"]?["result"]{
                    self.dataArray = innerDict as! [AnyObject]
                    print(self.dataArray)
                 if self.dataArray.count > 0
                  {
                    self.tableView.reloadData()
                  }
                }
            }
        }
    }

10-08 05:46