0

I am a newcomer to the ios app, writing a simple app that shows the api json data. The problem I am currently having is that I want to display the json data in the view, using the line chart to render

First of all, this is my json data.

{
TH_5min: [
{
Data: "2019-02-23T00:00:00",
Time: "11:00:00",
XTP_A: 10.5, //temperature 1
XHP_A: 11.5, //humidity 1
XTP_B: 33.5,
XHP_B: 44.6,
XTP_C: 88.9,
XHP_C: 66.6,
XTP_D: 77.9,
XHP_D: 99.6,
XTP_E: 87.87,
XHP_E: 66.66
},
{
Data: "2019-02-23T00:00:00",
Time: "11:05:00",
XTP_A: 55.2,  //temperature 1
XHP_A: 44.3,  //humidity 1
XTP_B: 66.6,
XHP_B: 77.87,
XTP_C: 87.77,
XHP_C: 87.87,
XTP_D: 8.87,
XHP_D: 78.78,
XTP_E: 87.78,
XHP_E: 87.87
}
]
}

This is the format I read json data and stored, using swift code

private var th_5mins = [Th_5min]() 
@objc func getlatestTh_5min(){
        guard let th_5minUrl = URL(string: kivaLoanURl) else{
            return
        }
        let request = URLRequest(url: th_5minUrl)
        let task = URLSession.shared.dataTask(with: request, completionHandler: {(data,response,error) -> Void in
            if let error = error {
                print(error)
                return
            }
            if let data = data {
                self.th_5mins = self.pardrJsonData(data: data)
            }
        })
        task.resume()
    }
    func pardrJsonData(data: Data) -> [Th_5min]{
        var th_5mins = [Th_5min]()
        do {
            let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
            let jsonTh_5mins = jsonResult?["TH_5min"] as! [AnyObject]
            for jsonTh_5min in jsonTh_5mins{
                var th_5min = Th_5min()
                th_5min.Data = jsonTh_5min["Data"] as! String
                th_5min.Time = jsonTh_5min["Time"] as! String
                th_5min.XTP_A = jsonTh_5min["XTP_A"] as! Double
                th_5min.XHP_A = jsonTh_5min["XHP_A"] as! Double
                th_5mins.append(th_5min)
            }        }catch{
                print(error)
        }
        return th_5mins
    }
}

Here is my current implementation of the line chart method, using swift code

override func viewDidLoad() {
        super.viewDidLoad()
        getlatestTh_5min()
        //
        chartView = LineChartView()
        chartView.frame = CGRect(x: 20, y: 80, width: self.view.bounds.width - 40,height: 300)
        self.view.addSubview(chartView)
        //Generate data for the first line chart
        var dataEntries1 = [ChartDataEntry]()
        for i in 0...5 {
            let y = Th_5min().XTP_A
            let entry = ChartDataEntry.init(x: Double(i), y: Double(y))
            dataEntries1.append(entry)
        }
        let chartDataSet1 = LineChartDataSet(entries: dataEntries1, label: "溫度")
        //Generate data for the second line chart
        var dataEntries2 = [ChartDataEntry]()
        for i in 0..<8 {
            let y = arc4random()%100
            let entry = ChartDataEntry.init(x: Double(i), y: Double(y))
            dataEntries2.append(entry)
        }
        let chartDataSet2 = LineChartDataSet(entries: dataEntries2, label: "濕度")
        //
        let chartData = LineChartData(dataSets: [chartDataSet1, chartDataSet2])
        //show line chart data
        chartView.data = chartData
    }

The current result is only the second line successfully displayed, but it is not the data I want. I only have a random value to display the data. The first one, no matter how you try, the json data is never lost in the chart. I want to implement it. All the data captured by the api (temperature 1, humidity 1) are thrown into the linechart, one shows the temperature and one shows the humidity, and the json's time is displayed in the upper X-axis part, but how to throw the json to the chart at present I don't know what to do, please help me!

1 Answer 1

1

There are two obvious problems here.

  1. At the start of viewDidLoad(), you call the function to download the JSON data. You then immediately try and plot the data. This will not work as the JSON data download is an asynchronous process, and will not have completed when the function returns. At this time you will not have access to the downloaded data. To fix this move the plot code from viewDidLoad() to a separate function, and call that function after the data is downloaded and parsed (i.e. at the end of pardrJsonData).
  2. The plotting code does not use the downloaded parsed JSON that you create in pardrJsonData. This function populates the th_5mins array, but it is not then used. The plot code includes let y = Th_5min().XTP_A, but this creates a new instance of the value and plots its XTP_A value which is default-initialised. Replace this line with let y = th_5mins[i].XTP_A. However, I'd change the loop limit from a hard-coded 5 to be for i in 0..<th_5mins.count.
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your explanation! But I don't know what "(i.e. at the end of pardrJsonData)" means, how should I adjust it in my swift code?Because I am not familiar with swift, I don't know how to adjust my swift code, please help me.
The current revision is successful! But I want to display the time in json just above my table, I don't know what to do.
I have another question, how do I adjust my line chart view to full screen
If this has helped you accomplish the original question then mark this as the answer. If not, let me know what is not working. If you have further questions then please ask new questions, do not add them as comments here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.