在swift 4

时间:2018-06-13 13:39:35

标签: ios json swift dictionary swift4.1

我正在使用此api并希望在表格视图上打印api数据

     import UIKit
     import Alamofire

     class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

      @IBOutlet weak var tableView: UITableView!
     @IBOutlet weak var mySegmentedControl: UISegmentedControl!





override func viewDidLoad() {
    super.viewDidLoad()

    apiData()
}

@IBAction func mySegmentControlTapped(_ sender: Any) {
    tableView.reloadData()
}


func apiData() {
    Alamofire.request("https://api.lrs.org/random-date-generator?lim_quarters=40&source=api-docs", 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}
            print("Response \(json)")
            guard let data = json["data"] as? [String:Any] else { return}
            print("data is \(data)")

            for (key, value) in data {
                print("\(key) -> \(value)")


            }

            break

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

        }
    }

}


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

    var returnValue = 0

    switch(mySegmentedControl.selectedSegmentIndex)
    {
    case 0:
        returnValue = day.count
        break
    case 1:
        returnValue = month.count
        break

    case 2:
        returnValue = db.count
        break

    case 3:
        returnValue = day.count
        break

    default:
        break

    }

    return returnValue
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let myCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! tableCell

    switch(mySegmentedControl.selectedSegmentIndex)
    {
    case 0:
        myCell.labelOne!.text = " "
        myCell.labelTwo!.text = ""
        myCell.labelThree!.text = ""
        myCell.labelFour!.text = ""
        break
    case 1:

        break

    case 2:

        break

    case 3:

        break

    default:
        break

    }
    return myCell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 90
}


}

class tableCell: UITableViewCell {

@IBOutlet weak var labelOne: UILabel!
@IBOutlet weak var labelTwo: UILabel!
@IBOutlet weak var labelThree: UILabel!
@IBOutlet weak var labelFour: UILabel!

   }

使用此代码后,我得到了键和值,我的问题是我在1键中得到6值。如何存储所有这些值并将其打印在tableview上。这是我正在做的全部代码我正在使用段控制器根据日期enter image description here

更改数据

4 个答案:

答案 0 :(得分:1)

试试这个:

for (key, value) in data {
    guard let innerDict = value as? [String: Any] else {
        continue
    }

    print(innerDict["day"])

}

要存储数据,您可以创建包含必要字段的简单类,并在此类中解析响应,然后将所有对象放入数组,然后放入tableview。

class MyData : NSObject {
    var dateTitle: String?
    var day: Int?
    var date: Date?
    var month: Int?
    var quarter: Int?

    override init() {
        super.init()
    }
}

// ....

// in parsing function
var result = [MyData]()
    for (key, value) in data {
        guard let innerDict = value as? [String: Any] else {
            continue
        }
        let obj = MyData()
        obj.day = innerDict["day"] as? Int
        // etc...
        result.append(obj)

}

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

答案 1 :(得分:1)

首先创建一个类来建模响应:

class CustomDate: NSObject {
    var quarter: Int!
    var day: String!
    var month: String!
    var db: String!
    var long: String!
    var unix: Int!

    init(quarter: Int, day: String, month: String, db: String, long: String, unix: Int) {
        super.init()

        self.quarter = quarter
        self.day = day
        self.month = month
        self.db = db
        self.long = long
        self.unix = unix
    }
}

然后创建一个数组来存储所有收到的日期:

var dates = [CustomDate]()

apiData的实施更改为:

func apiData() {
    Alamofire.request("https://api.lrs.org/random-date-generator?lim_quarters=40&source=api-docs", 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 = json["data"] as? [String: Any] else { return }

            for (_, value) in data {
                let dateValue = value as! [String: Any]
                let date = CustomDate(quarter: dateValue["quarter"] as! Int,
                                      day: dateValue["day"] as! String,
                                      month: dateValue["month"] as! String,
                                      db: dateValue["db"] as! String,
                                      long: dateValue["long"] as! String,
                                      unix: dateValue["unix"] as! Int)

                self.dates.append(date)
            }
            print(self.dates)
            self.tableView.reloadData()
            break
        case .failure(_):
            print(response.result.error as Any)
            break

        }
    }
}

然后,您唯一需要做的就是使用dates数组中的对象填充tableView:

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let date = dates[indexPath.row]

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    cell.textLabel.text = date.long
    return cell
}

当然,它需要根据您的需要进行调整。

答案 2 :(得分:0)

该值本身就是一个字典,因此您可以像这样访问各个字段

if let innerDict = value as? [String: Any] {
    print(\(innerDict["day"]))
    print(\(innerDict["db"]))
    ...
}

答案 3 :(得分:0)

声明字符串数组

var arrjsondata = [String:Any]()

中分配数据
arrjsondata = data
重新加载tableview后