Swift 4 Parse JSON без ключей с Alamofire - PullRequest
0 голосов
/ 13 июня 2018

Ребята, я хочу получить все имена из JSON (скриншот ниже) и поместить их в tableView.Проблема в том ... у меня есть словарь с этим кодом.Теперь, как я могу получить каждое значение имени и поместить их в tableView.

func getDataFromApi(){
    Alamofire.request("https://api.coinmarketcap.com/v2/listings/").responseJSON{ response in

        if let locationJSON = response.result.value{
            let locationObject: Dictionary = locationJSON as! Dictionary<String, Any>
            for (key, value) in locationObject {
                print("id:\(key), value:\(value)")
            }
        }
    }
}

enter image description here

Ответы [ 3 ]

0 голосов
/ 13 июня 2018

Я бы предложил преобразовать ответ словаря в объект Currency:

class Currency: NSObject {
    var id: Int!
    var name: String!
    var symbol: String!
    var websiteSlug: String!

    init(id: Int, name: String, symbol: String, websiteSlug: String) {
        super.init()

        self.id = id
        self.name = name
        self.symbol = symbol
        self.websiteSlug = websiteSlug
    }
}

Затем в разделе переменных определите массив currencies:

var currencies = [Currency]()

Окончательное изменениеgetDataFromApi реализация к этому:

func getDataFromApi() {
    Alamofire.request("https://api.coinmarketcap.com/v2/listings/").responseJSON{ response in
        if let locationJSON = response.result.value as? [String: Any] {
            let data = locationJSON["data"] as! [[String: Any]]
            for dataItem in data {
                let currency = Currency(id: dataItem["id"] as! Int,
                                        name: dataItem["name"] as! String,
                                        symbol: dataItem["symbol"] as! String,
                                        websiteSlug: dataItem["website_slug"] as! String)

                self.currencies.append(currency)
            }

            print(self.currencies)
        }
    }
}

Я всегда предлагаю смоделировать ответы на объекты, потому что это позволяет вам лучше управлять данными, которые необходимо отображать на экране, и поддерживать структуру кода.

Теперь вы можете легко отобразить данные в объекте UITableView из массива currencies.

0 голосов
/ 13 июня 2018

Я бы предложил преобразовать ответ словаря Array In в объект Currency:

 var dataArray = NSArray()
        @IBOutlet var tableView: UITableView!
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a 
        nib.
            self.getDataFromApi()
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
        func getDataFromApi(){
            Alamofire.request("https://api.coinmarketcap.com/v2/listings/").responseJSON{ response in

                if let locationJSON = response.result.value{
                    let locationObject: Dictionary = locationJSON as! Dictionary<String, Any>
                    self.dataArray = locationObject["data"]as! NSArray
                    self.tableView.reloadData()

    //                for (key, value) in locationObject {
    //                    print("id:\(key), value:\(value)")
    //                }
                }
            }
        }
        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
           return dataArray.count
        }
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier:"cell") as! UITableViewCell
            cell.textLabel?.text = (dataArray.object(at:indexPath.row) as! NSDictionary).value(forKey:"name") as! String
            cell.detailTextLabel?.text = (dataArray.object(at:indexPath.row) as! NSDictionary).value(forKey:"symbol") as! String
            return cell
        }
0 голосов
/ 13 июня 2018
var nameArray = [String]()


override func viewDidLoad() {
 super.viewDidLoad()

    getData()
 }

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

  return nameArray.count
 }

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

let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! tableCell
cell.nameLabel.text = nameArray[indexPath.row]
return cell

 }

func alamofire() {
  Alamofire.request("https://api.coinmarketcap.com/v2/listings/", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

    switch(response.result) {
    case .success(_):
        guard let json = response.result.value as! [String:Any] else{ return}
        guard let data = ["data"] as! [[String: Any]] else { return}

        for item in data {

            if let name = item["name"] as? String {
                self.nameArray.append(name)
            }

            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }


        break

    case .failure(_):
        print(response.result.error as Any)
        break

    }
}

}
...