Swift - 使用图表在饼图中显示JSON数据

时间:2018-02-21 09:17:37

标签: ios swift charts alamofire

我试图在图表库的帮助下在饼图中显示获取的JSON数据。但是无法将数组数据分配给图表,因为获取的JSON数据是键值对的形式,并且在设置图表时,需要简单的数组。请帮助朋友,任何帮助将不胜感激。提前致谢

import UIKit
import Charts
import Alamofire
import SwiftyJSON

class CertificateChartView: UIViewController {

    // Pie chart view
    @IBOutlet weak var pie: PieChartView!

    //Certificate Image Url
    let certificateImageURL = "--my url string--"

    // Temporary array dictionary
    var tempArray = [[String : AnyObject]]()

    override func viewDidLoad() {
        super.viewDidLoad()

//        getCertificates()

        let months = ["Jan", "Feb","Mar"]
        let unitsSold = [25.0, 45.0, 36.0]
        setChart(dataPoints: months, values: unitsSold)
        pie.chartDescription?.text = ""
        pie.noDataText = "You need to provide data for the chart"

    }


//    function for Pie chart 
    func setChart(dataPoints: [String], values: [Double]) {
        var dataEntries: [ChartDataEntry] = []
        for i in 0..<dataPoints.count {
            let dataEntry1 = ChartDataEntry(x: Double(i), y: values[i], data: dataPoints[i] as AnyObject)
            dataEntries.append(dataEntry1)
        }
        //        print(dataEntries[0].data)
        let pieChartDataSet = PieChartDataSet(values: dataEntries, label: "")
        let pieChartData = PieChartData(dataSet: pieChartDataSet)
        pie.data = pieChartData
        pie.centerText = "Certificate"
        var colors: [UIColor] = []
        for _ in 0..<dataPoints.count {
            let red = Double(arc4random_uniform(256))
            let green = Double(arc4random_uniform(256))
            let blue = Double(arc4random_uniform(256))
            let color = UIColor(red: CGFloat(red/255), green: CGFloat(green/255), blue: CGFloat(blue/255), alpha: 1)
            colors.append(color)
        }
        pieChartDataSet.colors = colors
    }


    func getCertificates() {
        Alamofire.request(certificateImageURL).responseJSON { response in
            if((response.result.value) != nil) {
                let swiftyJsonVar = JSON(response.result.value!)
                if let resData = swiftyJsonVar["data"].arrayObject {
                    self.tempArray = resData as! [[String:AnyObject]]
//                    print(self.tempArray.count)
                }
            }
        }
    }
}

JSON数据

 {
  data: [
    {
      cert_id: "1",
      cert_issue_date: "12/04/2017",
      cert_expiry_date: "12/09/2017"
    },
    {
      cert_id: "2",
      cert_issue_date: null,
      cert_expiry_date: "01/31/2018"
    },
    {
      cert_id: "3",
      cert_issue_date: null,
      cert_expiry_date: "02/02/2018"
    }
  ]
}

OUTPUT SCREENSHOT

Pie Chart Output

0 个答案:

没有答案