无法使用Alamofire&amp ;;在tableviewcell中加载JSON数据SwiftyJSON

时间:2018-03-26 04:07:49

标签: swift cocoapods alamofire swifty-json

我想加载名称& textLabel&中加密货币的象征detailTextLabel

TableViewController.swift: -

import UIKit
import Alamofire
import SwiftyJSON


class TableViewController: UITableViewController {

    var fetchCoinInfo = [[String: AnyObject]]()
    let url = "https://api.coinmarketcap.com/v1/ticker/"

    override func viewDidLoad() {
        super.viewDidLoad()
        getCoinData(url: url)
        self.tableView.reloadData()
    }


   //  MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return fetchCoinInfo.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

        cell.textLabel?.text = fetchCoinInfo[indexPath.row]["name"] as? String
        cell.detailTextLabel?.text = fetchCoinInfo[indexPath.row]["symbol"] as? String

        return cell
    }

使用Alamofire: -

  func getCoinData(url: String) {

        Alamofire.request(url, method: .get)
            .responseJSON { response in
                if response.result.isSuccess {

                    print("Sucess! Got the data")
                    let coinJSON : JSON = JSON(response.result.value!)
                    print(coinJSON)
                   self.updateCoinData(json: coinJSON)

                } else {
                    print("Error: \(String(describing: response.result.error))")
            }
        }
        self.tableView.reloadData()
    }

  Using SwiftyJSON :-

    func updateCoinData(json : JSON) {

        if let coinData = json[].arrayObject {
            print(coinData)

            self.fetchCoinInfo = coinData as! [[String: AnyObject]]
        }
        else {
            print("cannot connect to the server")
        }
    }

}

1 个答案:

答案 0 :(得分:1)

将此行放在updateCoindata中 self.tableView.reloadData()

func updateCoinData(json : JSON) {

        if let coinData = json[].arrayObject {
            print(coinData)

            self.fetchCoinInfo = coinData as! [[String: AnyObject]]
             self.tableView.reloadData()

         }
        else {
            print("cannot connect to the server")
        }
    }