Search code examples
iosios-charts

iOS Charts library - not able to bind data to chart view


I am using charts library and want to display a bar chart. I am facing issue for binding the data to the chart.This is my code.

class FirstViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

@IBOutlet weak var barChartView: BarChartView!
@IBOutlet weak var yearDropDown: UIPickerView!

@IBOutlet weak var rmDropDown: UIPickerView!

@IBOutlet weak var txtYear: UITextField!
@IBOutlet weak var txtRm: UITextField!

var months = [String]()


override func viewDidLoad() {
super.viewDidLoad()

        months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0, 4.0, 18.0, 2.0, 4.0, 5.0, 4.0]


        getYear()
        setChart(dataPoints: months, values: unitsSold)

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func getYear()
{
    url = RestMonitorServer.baseUrl + "/foo/bar"
    Alamofire.request(url, method: .get, parameters: ["foo": bar,"foo":bar,"foo":bar])
        .responseJSON(){
    (response) in
            print("get year list response ",response)

            if ((response.result.value) != nil) {
                let jsonData = JSON(response.result.value!)

                if jsonData["duration"].arrayObject != nil {
                    self.durationArray.append("duration")
                    print("duration array ", self.durationArray)
                }

            } else if (((response.error)) != nil) {
                let jsonError = response.error
                print("Error in getting year list ", jsonError as Any)
            }

    }

}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    return durationArray.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {


    if pickerView == yearDropDown {

        let titleRow = durationArray[row]

        return titleRow
    }
    return ""
}

func setChart(dataPoints: [String], values: [Double]) {

    var dataEntries: [BarChartDataEntry] = []

    for i in 0..<dataPoints.count {
        let dataEntry = BarChartDataEntry(x:values[i],y:Double(i))
        dataEntries.append(dataEntry)
    }
    print("data entries ",dataEntries)
    let chartDataSet = BarChartDataSet(values: dataEntries, label: "Units Sold")
    print("chart data set ", chartDataSet)
    let chartData = BarChartData(dataSets: [chartDataSet])
    print("chart data ",chartData)
    barChartView.data = chartData //error at this line as fatal error: unexpectedly found nil while unwrapping an Optional value
    print("bar chart data" , barChartView.data!)   
}

}

This is my full code. And I am getting error for barChartView which I have initialised as above, but it still giving me error.

Thanks


Solution

  • As per my exp you need to move your function to BarChartView extension like below :

    extension BarChartView {
    
        func setBarChartData(xValues: [String], yValues: [Double], label: String) {
    
            var dataEntries: [BarChartDataEntry] = []
    
            for i in 0..<yValues.count {
                let dataEntry = BarChartDataEntry(x: Double(i), y: yValues[i])
                dataEntries.append(dataEntry)
            }
    
            let chartDataSet = BarChartDataSet(values: dataEntries, label: label)
            let chartData = BarChartData(dataSets: [chartDataSet])
    
            self.data = chartData
    
        }
    }
    

    and Call it like below :

    override func viewDidLoad() {
            super.viewDidLoad()
            barChartView.setBarChartData(xValues: months, yValues: unitsSold, label: "Monthly Sales")
    }
    

    Try this and let me know is it working or not.

    Also one more thing you are setting static data of months & values my question is where are you filling server response data ?