如何使用图表库分离JSON数据以进行唯一显示?

时间:2017-07-06 09:03:30

标签: ios charts swift3 alamofire

我可以使用Charts Library显示JSON数据以显示折线图。我显示了所有标记和主题但我试图在 TermWise 中显示。如何使用TermID分隔JSON数据?

import UIKit
import Charts
import Alamofire
import SwiftyJSON


class ViewController: UIViewController , ChartViewDelegate{


    @IBOutlet weak var text: UILabel!
    @IBOutlet weak var lineChartView: LineChartView!
    @IBOutlet weak var menu: UIBarButtonItem!
    var login_details : Login?
    var markdetail : [Marks] = []
    var markd : Marks?
    var myResponse  :   JSON    =   nil
//    var Subjects: [String] = []
    var subjectss : [String] = []
    var marks01 : [Double] = []
    var setname = String()

    let Subjects = ["eng" , "sci", "math", "soc"]
    let marks1 = [45,55,70,80]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        menu.target = self.revealViewController()

        menu.action = #selector(SWRevealViewController.revealToggle(_:))

        if self.revealViewController() != nil {

            self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
            self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer())
        }

//        text.text = markd?.NAME

//        forlineView()
        getmarks()



    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func getmarks(){
        let student_id = login_details?.masterid
        let std_id_String = student_id?.replacingOccurrences(of: "[^0-9 ]", with: "", options: NSString.CompareOptions.regularExpression, range:nil)
        print("numberic",std_id_String!)

        let url = NSURL(string: "http://**********/api/academics//getSingleStudentsMarks"+"?StdID=" + std_id_String!)
        var request = URLRequest(url: url! as URL)
        request.httpMethod = "GET"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        Alamofire.request(request).responseJSON(){ response in
            switch response.result{
            case.success(let data):
                print("success",data)

                let myresponse = JSON(data)
                for marks in myresponse.array!{
                    let marksObj = Marks(MarksJson: marks)
                    self.markdetail.append(marksObj)

                    self.subjectss.append(marksObj.CourseName)
                    self.marks01.append(marksObj.marks)
//                    for name in markdetail{
//                    
//                    }

                    self.setname.append(marksObj.examDescription)

                    print("Markss",marksObj.marks)
                    self.forlineView()
                    self.textdisplay()
                }


            case.failure(let error):
                print("Not Success",error)
            }

        }
    }


    func forlineView() {
        // 1
        self.lineChartView.delegate = self
        // 2
        self.lineChartView.chartDescription?.text = "Tap node for details"
        // 3
        self.lineChartView.chartDescription?.textColor = UIColor.red
        self.lineChartView.gridBackgroundColor = UIColor.darkGray
//        self.lineChartView.backgroundColor = UIColor.darkGray
        // 4
        self.lineChartView.noDataText = "No data provided"
        // 5
        setChartData(subject: subjectss)

    }

    func setChartData(subject : [String]) {

        // 1 - creating an array of data entries
        var yVals1 : [ChartDataEntry] = [ChartDataEntry]()

        for i in 0..<subject.count {
            yVals1.append(ChartDataEntry(x: Double(i), y: Double(marks01[i])))
        }

        // 2 - create a data set with our array
        let set1: LineChartDataSet = LineChartDataSet(values: yVals1, label: setname)
        set1.axisDependency = .left // Line will correlate with left axis values
        set1.setColor(UIColor.red.withAlphaComponent(0.5)) // our line's opacity is 50%
        set1.setCircleColor(UIColor.red) // our circle will be dark red
        set1.lineWidth = 2.0
        set1.circleRadius = 6.0 // the radius of the node circle
        set1.fillAlpha = 65 / 255.0
        set1.fillColor = UIColor.red
        set1.highlightColor = UIColor.red
        set1.drawCircleHoleEnabled = true

        //3 - create an array to store our LineChartDataSets
        var dataSets : [LineChartDataSet] = [LineChartDataSet]()
        dataSets.append(set1)

        //4 - pass our months in for our x-axis label value along with our dataSets
        let data: LineChartData = LineChartData(dataSets: dataSets)
        data.setValueTextColor(UIColor.red)

        //5 - finally set our data
        self.lineChartView.data = data

        //6 - add x-axis label
        let xaxis = self.lineChartView.xAxis
        xaxis.valueFormatter = MyXAxisFormatter(subject)

    }




    func textdisplay(){
        for d in self.markdetail{

            self.text.text = d.NAME

        }
    }


}

class MyXAxisFormatter: NSObject, IAxisValueFormatter {

    let subjectss: [String]

    init(_ subjects: [String]) {
        self.subjectss = subjects
    }

    func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        return subjectss[Int(value) % subjectss.count]
    }

}

目前我正在

enter image description here

JSON

 (
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 4027;
        CourseName = Arts;
        Marks = 45;
        NAME = "Calvin Patterson";
        Sno = 2107;
        StdID = 95;
        TermID = 6022;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = "First Term";
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 5034;
        CourseName = Math;
        Marks = 90;
        NAME = "Calvin Patterson";
        Sno = 2108;
        StdID = 95;
        TermID = 6022;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = "First Term";
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 5035;
        CourseName = English;
        Marks = 52;
        NAME = "Calvin Patterson";
        Sno = 2109;
        StdID = 95;
        TermID = 6022;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = "First Term";
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 6034;
        CourseName = hi;
        Marks = 70;
        NAME = "Calvin Patterson";
        Sno = 2110;
        StdID = 95;
        TermID = 6022;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = "First Term";
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 4027;
        CourseName = Arts;
        Marks = 50;
        NAME = "Calvin Patterson";
        Sno = 4119;
        StdID = 95;
        TermID = 7024;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = Second;
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 5034;
        CourseName = Math;
        Marks = 60;
        NAME = "Calvin Patterson";
        Sno = 4120;
        StdID = 95;
        TermID = 7024;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = Second;
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 5035;
        CourseName = English;
        Marks = 70;
        NAME = "Calvin Patterson";
        Sno = 4121;
        StdID = 95;
        TermID = 7024;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = Second;
        type = Terminal;
    },
        {
        CLASSNO = 1;
        "CLASS_ID" = 2021;
        CourseID = 6034;
        CourseName = hi;
        Marks = 80;
        NAME = "Calvin Patterson";
        Sno = 4122;
        StdID = 95;
        TermID = 7024;
        "Terminal_FM" = 100;
        "Terminal_PM" = 40;
        "UT_FM" = 50;
        "UT_PM" = 20;
        examDescription = Second;
        type = Terminal;
    }
)

需要

enter image description here

  

我在图表中显示了所有JSON数据。我想显示标记和   TermWise中的主题。如何完成?我想要显示标记和   第一学期和第二学期的科目,这些术语有相同的科目,但   标记是不同的,并希望在同一图表中绘图

模型类

class Marks {
    var classno = String()
    var class_id = String()
    var  course_id = String()
    var marks = Double()
    var Sno = String()
    var stdid = String()
    var TermID = String()
    var CourseName = String()
    var Terminal_FM = String()
    var Terminal_PM = String()
    var UT_FM = String()
    var UT_PM = String()
    var examDescription = String()
    var type =  String()
    var transferRate = String()
    var NAME = String()

    init(MarksJson:JSON) {
        self.classno = MarksJson["CLASSNO"].stringValue
        self.class_id = MarksJson["CLASS_ID"].stringValue
        self.course_id = MarksJson["CourseID"].stringValue
        self.marks = MarksJson["Marks"].double!
        self.Sno = MarksJson["Sno"].stringValue
        self.stdid = MarksJson["StdID"].stringValue
        self.TermID = MarksJson["TermID"].stringValue
        self.CourseName = MarksJson["CourseName"].stringValue
        self.Terminal_FM = MarksJson["Terminal_FM"].stringValue
        self.Terminal_PM = MarksJson["Terminal_PM"].stringValue
        self.UT_FM = MarksJson["UT_FM"].stringValue
        self.UT_PM = MarksJson["UT_PM"].stringValue
        self.examDescription = MarksJson["examDescription"].stringValue
        self.type =  MarksJson["type"].stringValue
        self.transferRate = MarksJson["transferRate"].stringValue
        self.NAME = MarksJson["NAME"].stringValue

    }


}

1 个答案:

答案 0 :(得分:1)

Change your code like this, 




     for marks in myresponse.array!
        {
        let marksObj = Marks(MarksJson: marks)
        if marksObj.examDescription == "First Term"
        {
        self.markdetail.append(marksObj)
        self.subjectss.append(marksObj.CourseName)
        self.marks01.append(marksObj.marks)
        self.setname = marksObj.examDescription
        print("Markss",marksObj.marks)
        self.forlineView(examDescription: marksObj.examDescription)
        self.textdisplay(marks: marksObj)
        }
        else if marksObj.examDescription == "Second Term"
        {
        self.markdetailForSecondTerm.append(marksObj)
        self.subjectssForSecondTerm.append(marksObj.CourseName)
        self.marks01ForSecondTerm.append(marksObj.marks)
        self.setname = marksObj.examDescription
        print("Markss",marksObj.marks)
        self.forlineView(examDescription: marksObj.examDescription)
        self.textdisplay(marks: marksObj)
        }
        }
    }

    func forlineView(examDescription: String)
    {
        if examDescription ==  "First Term"
        {
            // 1
            self.lineChartView.delegate = self
            // 2
            self.lineChartView.chartDescription?.text = "Tap node for details"
            // 3
            self.lineChartView.chartDescription?.textColor = UIColor.red
            self.lineChartView.gridBackgroundColor = UIColor.darkGray
            //        self.lineChartView.backgroundColor = UIColor.darkGray
            // 4
            self.lineChartView.noDataText = "No data provided"
            // 5
            setChartData(subject: subjectss,marks: marks01,exam: examDescription)
        }
        else if examDescription ==  "Second Term"
        {
            // 1
            self.lineChartView.delegate = self
            // 2
            self.lineChartView.chartDescription?.text = "Tap node for details"
            // 3
            self.lineChartView.chartDescription?.textColor = UIColor.green
            self.lineChartView.gridBackgroundColor = UIColor.darkGray
            //        self.lineChartView.backgroundColor = UIColor.darkGray
            // 4
            self.lineChartView.noDataText = "No data provided"
            // 5
            setChartData(subject: subjectssForSecondTerm,marks: marks01ForSecondTerm,exam: examDescription)
        }
    }

    func setChartData(subject : [String], marks : [Double], exam: String) {

    // 1 - creating an array of data entries
    var yVals1 : [ChartDataEntry] = [ChartDataEntry]()
    if (exam == "First Term")
    {

        for i in 0..<subject.count {
            yVals1.append(ChartDataEntry(x: Double(i), y: Double(marks[i])))
        }
        // 2 - create a data set with our array
        let set1: LineChartDataSet = LineChartDataSet(values: yVals1, label: "First Term")
        set1.axisDependency = .left // Line will correlate with left axis values
        set1.setColor(UIColor.red.withAlphaComponent(0.5)) // our line's opacity is 50%
        set1.setCircleColor(UIColor.red) // our circle will be dark red
        set1.lineWidth = 2.0
        set1.circleRadius = 6.0 // the radius of the node circle
        set1.fillAlpha = 65 / 255.0
        set1.fillColor = UIColor.red
        set1.highlightColor = UIColor.red
        set1.drawCircleHoleEnabled = true

        //3 - create an array to store our LineChartDataSets
        dataSets.append(set1)

        //4 - pass our months in for our x-axis label value along with our dataSets

    }

    else if (exam == "Second Term")
    {
        var yVals2 : [ChartDataEntry] = [ChartDataEntry]()
        for i in 0..<subject.count {
            yVals2.append(ChartDataEntry(x: Double(i), y: Double(marks[i])))
        }
        // 2 - create a data set with our array
        let set2: LineChartDataSet = LineChartDataSet(values: yVals2, label: "Second Term")
        set2.axisDependency = .left // Line will correlate with left axis values
        set2.setColor(UIColor.red.withAlphaComponent(0.5)) // our line's opacity is 50%
        set2.setCircleColor(UIColor.red) // our circle will be dark red
        set2.lineWidth = 2.0
        set2.circleRadius = 6.0 // the radius of the node circle
        set2.fillAlpha = 65 / 255.0
        set2.fillColor = UIColor.red
        set2.highlightColor = UIColor.red
        set2.drawCircleHoleEnabled = true

        //3 - create an array to store our LineChartDataSets
        dataSets.append(set2)


    }

    let data: LineChartData = LineChartData(dataSets: dataSets)
    data.setValueTextColor(UIColor.red)

    //5 - finally set our data
    self.lineChartView.data = data

    //6 - add x-axis label
    let xaxis = self.lineChartView.xAxis
    xaxis.valueFormatter = MyXAxisFormatter(subject)

}

    func textdisplay(markDetails: [Marks]){
        for d in self.markDetails{

            self.text.text = d.NAME

        }
    }