While parsing JSON data, I get different result, from same url - ios

Problem Statement: Every time whenever I refresh viewController, then I get different values.
Required Solution: Whenever I refresh, it should fetch same values.
Coding Stuff:
Below I have get values from JSON parsing via url. After fetching values, it pass to the 'setChart() function as a parameter.'
override func viewDidLoad()
{
super.viewDidLoad()
var completedCalls = 0
for i in 0..<strDates.count {
Alamofire.request("http://api.fixer.io/\(strDates[i])?base=USD").responseJSON { response in
if let arr = response.result.value as? [String:AnyObject]
{
completedCalls += 1
let inrc = (arr["rates"]?["INR"] as? Double)!
print(inrc)
self.sValues.append(inc)
print(sValues)
//It prints values here.
if completedCalls = strDates.count {
DispatchQueue.main {
setChart(dataPoints: strDates, values: sValues)
}
}
}
}
}
setChart() Function
func setChart(dataPoints: [String], values: [Double]) {
barChartView.noDataText = "You need to provide data for the chart."
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(x: Double(i), yValues: [values[i]])
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(values: dataEntries, label: "INR Rates(₹)/$")
let chartData = BarChartData(dataSet: chartDataSet)
barChartView.data = chartData
barChartView.leftAxis.axisMinimum = 65
barChartView.leftAxis.axisMaximum = 70
barChartView.xAxis.labelPosition = .bottom
barChartView.rightAxis.enabled = false
barChartView.data?.setDrawValues(false)
}
}

You're issuing a sequence of asynchronous requests, but you have no assurances the order in which they'll complete.
I would suggest capturing the results in a dictionary, with the strDates as the key. Then you can extract them in the correct order when presenting the results.
So, I'm assuming that assuming that sValues is defined as:
var sValues = [Double]()
Change that to:
var sValues = [String: Double]()
And then, rather than:
self.sValues.append(inc)
You would do:
self.sValues[strDates[i]] = inc
Then, in your charting code, iterate through strDates array, and look up the sValues using those date strings.

Related

How to show json data in line chart using swift

I am trying to design an ios app to display json data in a line chart.
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 my implementation of the swift code showing json data.
override func viewDidLoad() {
super.viewDidLoad()
apiip = APIip
getlatestTh_5min()
#objc func getlatestTh_5min(){
guard let th_5minUrl = URL(string: "http://" + apiip + "/api/Th_5min") 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)
self.getchat()
}
})
task.resume()
//getchat()
}
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]
print(jsonTh_5mins)
print(th_5mins.count)
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
print(th_5min)
th_5mins.append(th_5min)
//getchat()
} }catch{
print(error)
}
//getchat()
return th_5mins
}
This is how I draw the line chart, using swift code.
#objc func getchat(){
chartView = LineChartView()
chartView.frame = CGRect(x: 20, y: 80, width: self.view.bounds.width-20,height: self.view.bounds.height-100)
self.view.addSubview(chartView)
var dataEntries1 = [ChartDataEntry]()
for i in 0..<th_5mins.count {
chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: [th_5mins[i].Time])
let y = th_5mins[i].XTP_A
let entry = ChartDataEntry.init(x: Double(i), y: Double(y))
dataEntries1.append(entry)
}
let chartDataSet1 = LineChartDataSet(entries: dataEntries1, label: "temperature")
chartDataSet1.colors = [NSUIColor.red]
var dataEntries2 = [ChartDataEntry]()
for i in 0..<th_5mins.count {
chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: [th_5mins[i].Time])
let y = th_5mins[i].XHP_A
let entry = ChartDataEntry.init(x: Double(i), y: Double(y))
dataEntries2.append(entry)
}
let chartDataSet2 = LineChartDataSet(entries: dataEntries2, label: "humidity")
chartDataSet2.colors = [NSUIColor.black]
let chartData = LineChartData(dataSets: [chartDataSet1, chartDataSet2])
chartView.data = chartData
}
}
This is the result of my work.
enter image description here
Although the json data is successfully displayed, I don't know why it is loading for a long time, and I hope that the "time" in my json data can be displayed on the X axis above, marked with my temperature and humidity, and cannot be successful.
I also hope that my line chart view can be implemented as a layout.
"I don't know why it is loading for a long time". Do you mean that the graph does not load immediately upon opening the view? This is because the data is loading asynchronously from a remote source (correctly now, well done). It may well take a few seconds for your JSON to download over the web. That is ok. You can test the endpoint in a browser and see how long the response takes.
"I hope that the 'time' in my json data can be displayed on the X axis above". Yes. You can take the assignation of IndexAxisValueFormatter outside of the loop and you should pass all labels as values into the constructor. Try this code, replacing the equivalent loop:-
var labels: [String] = []
for i in 0..<th_5mins.count {
let y = th_5mins[i].XTP_A
let entry = ChartDataEntry.init(x: Double(i), y: Double(y))
dataEntries1.append(entry)
labels.append(th_5mins[i].Time)
}
chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: labels)
Note that the method you use for plotting against dates will result in an evenly spread graph, irrespective of your time gaps (e.g. if readings are 5 mins apart between the first two, but 5 years apart for the next two, they will still appear with even gaps between them.

Candlestick chart not appearing correctly in ios using danielgindi/Charts framework

var dataEntries: [ChartDataEntry] = []
let financialData = data
for chartData in financialData{
let dataEntry = CandleChartDataEntry(x: chartData.date, shadowH: chartData.High, shadowL: chartData.Low, open: chartData.Open, close: chartData.Close)
dataEntries.append(dataEntry)
}
let chartDataSet = CandleChartDataSet(values: dataEntries, label: "")
chartDataSet.axisDependency = .left
chartDataSet.drawValuesEnabled = false
chartDataSet.increasingColor = UIColor.green
chartDataSet.increasingFilled = false
chartDataSet.decreasingColor = UIColor.red
chartDataSet.decreasingFilled = true
chartDataSet.barSpace = 0.25
chartDataSet.shadowColor = UIColor.darkGray
chartDataSet.neutralColor = UIColor.blue
let chartData = CandleChartData(dataSet: chartDataSet)
chartView.data = chartData
let xaxis = chartView.xAxis
xaxis.valueFormatter = axisFormatDelegate
Below is the sample data set that is being received from server and the image showing the chart being displayed.
https://api.cryptowat.ch/markets/gdax/btcusd/ohlc?periods=60
[ CloseTime, OpenPrice, HighPrice, LowPrice, ClosePrice, Volume ]
I need help in fixing the display of data as currently it doesn't resemble a candle stick chart in any way. Can someone please help me in what I am doing wrong here.
CandleStick chart data being displayed in the app
So just in case anyone is having the same problem, i was having issues with the candles too and i found a solution based on this post:
https://github.com/danielgindi/Charts/issues/2742
Create a class for your chartView.xAxis.valueFormatter that supports your entries with your init.
Once you have your results entries, i used the enumerated value for the x on the CandleChartDataEntry
In the stringForValue method inside your class that inherits from IAxisValueFormatter work the way you want to present your string, in my case was dates.
First two points:
//Check nil results
if result != nil {
//Save to Holder for future use
self.historyData = result
// Set the formatter class for the chartView
self.chartView.xAxis.valueFormatter = dateFormatter(elementsForFormatter: self.historyData!)
//Create a new chart data entry
var chartEntries = [ChartDataEntry]()
//Loop results
result?.enumerated().forEach({ (i, element) in
// I'm force unwrapping, but please take care of this don't do me...
let newDataEntryValue = CandleChartDataEntry(x:Double(i),
shadowH: element["high"] as! Double,
shadowL: element["low"] as! Double,
open: element["open"] as! Double,
close: element["close"] as! Double)
chartEntries.append(newDataEntryValue)
})
}
// Do rest of conf. for your chart....
Last point (class implementation):
class dateFormatter: IAxisValueFormatter {
var elements:Array<Dictionary<String,Any>>
init(elementsForFormatter:Array<Dictionary<String,Any>>) {
self.elements = elementsForFormatter
}
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
let formatter = DateFormatter()
formatter.dateStyle = .short
//Get the date based on the value which is the index
if let time = self.elements[Int(value)]["time"] as? Double {
print(time)
let dateString = formatter.string(from: Date(timeIntervalSince1970: TimeInterval(time)))
return dateString
} else {
return ""
}
}
}
Hope this helps someone!

How to iterate through Swift array and use data in iOS Chart?

I have a bar chart, which I am trying to populate through data pulled in from an array.
I am trying to iterate through this array in order to populate my chart.
Please note: in this example below there are 3 winningStreakDM variables hardcoded for testing purposes, but in 'real life' the number could be different each API call as it depends on how many 'users' are in that league.
This is why I need to iterate through the array and structure the data to suit.
let winningStreakDM1 : [String : Any] = [
"id" : 2,
"user_name" : "Dicky",
"winning_streak" : 5
]
let winningStreakDM2 : [String : Any] = [
"id" : 6,
"user_name" : "G",
"winning_streak" : 2
]
let winningStreakDM3 : [String : Any] = [
"id" : 5,
"user_name" : "Sultan",
"winning_streak" : 0
]
My issue is that I don't know how to iterate through the initial array to structure my data for it to work with the above code.
This is my full script:
import UIKit
import Charts
class CommunityLeagueStatsVC: UIViewController {
// GRAPHS *********
#IBOutlet weak var chartView: BarChartView!
var values = [BarChartDataEntry]()
// ****************
//********CHART VARIABLES**************//
//WINS LOSSES DRAWS
var winStreak: Double = 0.0
#IBOutlet weak var leagueStatsScrollView: UIScrollView!
var noDefeats: Bool?
var noWins: Bool?
var biggestWin: String?
var biggestWinTeams: String?
var passedCommunityName: String?
#IBOutlet weak var communityName: UILabel!
var playerId2: String?
var communityId2: String?
var eMail2: String?
override func viewDidLoad() {
super.viewDidLoad()
let winningStreak = ["Wins"]
let gamesWon = [winStreak]
setWinStreakChart(dataPoints: winningStreak, values: gamesWon)
let defaults = UserDefaults.standard
let Email = defaults.string(forKey: "userEmail")
let playerId = defaults.string(forKey: "playerId")
let commsId = defaults.string(forKey: "communityId")
self.playerId2 = playerId
self.communityId2 = commsId
self.eMail2 = Email
}
func setWinStreakChart(dataPoints: [String], values: [BarChartDataEntry]){
xAxis.valueFormatter = WinningStreakFormatter(chartView: self.chartView)
let barChartDataSet = BarChartDataSet(values: values, label: "Winning Streak")
barChartDataSet.colors = ChartColorTemplates.material()
let barChartData = BarChartData(dataSet: barChartDataSet)
barChartData.setValueFont(UIFont.systemFont(ofSize: 12.0))
self.chartView.data = barChartData
}
override func viewDidAppear(_ animated: Bool) {
let myUrl = URL(string: "http://www.xxx.uk/xxx/getLeagueStats.php")
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
let postString = "player_id=\(self.playerId2!)&community_id=\(communityId2!)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
print (json!)
if let dict = json?["leagueStats"] as? [String:AnyObject] {
//WINNING STREAK
var values = [BarChartDataEntry]()
if let dataWinStreak = dict["winningStreak"] as? [[String : Any]] {
print ("test one")
for (index,item) in dataWinStreak.enumerated() {
if let yValue = item["winning_streak"] as? Int, let userName = item["user_name"] as? String {
print ("test two")
let barChartDataEntry = BarChartDataEntry(x: Double(index), y: Double(yValue), data: userName as AnyObject?)
values.append(barChartDataEntry)
}
}
self.setWinStreakChart(dataPoints: ["wins"], values: values)
}
catch{
print(error)
}
}
}
task.resume()
}
}
UPDATE:
These are the errors that I am currently receiving:
With a bit of playing around and commenting out the line containing the first error I have got to this stage which correctly shows a graph with values, but no xAxis containing the userNames of each player.
You can create array of BarChartDataEntry this way.
var values = [BarChartDataEntry]()
if let dataWinStreak = dict["winningStreak"] as? [[String : Any]] {
for (index,item) in dataWinStreak.enumerated() {
if let yValue = item["winning_streak"] as? Int, let userName = item["user_name"] as? String {
let barChartDataEntry = BarChartDataEntry(x: index, y: yValue, data: userName)
values.append(barChartDataEntry)
}
}
}
//Now use values array
Edit: You just need to change setWinStreakChart function because now you are working with dynamic data not static one.
func setWinStreakChart(dataPoints: [String], values: [BarChartDataEntry]){
let xAxis : XAxis = self.chartView.xAxis;
xAxis.labelFont = UIFont(name: "HelveticaNeue-Light", size: 10.0)!
xAxis.labelTextColor = UIColor.black
xAxis.drawAxisLineEnabled = false
xAxis.drawGridLinesEnabled = true
xAxis.granularity = 1;
xAxis.labelPosition = .bottom
xAxis.valueFormatter = WinningStreakFormatter(chartView: self.chartView)
let barChartDataSet = BarChartDataSet(values: values, label: "Winning Streak")
barChartDataSet.colors = ChartColorTemplates.material()
let barChartData = BarChartData(dataSet: barChartDataSet)
barChartData.setValueFont(UIFont.systemFont(ofSize: 12.0))
self.chartView.data = barChartData
}
And now call this function after the for loop where we are creating array of BarChartDataEntry.
self.setWinStreakChart(dataPoints: ["wins"], values: values)

How to add labels for XAxis for BarChartView in ios-charts

I added a bar chart to the storyboard, but I cannot properly set labels for my data entries.
here is my code:
var names = ["aaa", "bbb", "ccc", "ddd"]
var values = [230.0, 280.0, 450.0, 340.0]
setChart(dataPoints: names, values: values)
setChart function:
func setChart(dataPoints: [String], values: [Double])
{
let formatter = BarChartFormatter()
formatter.setValues(values: dataPoints)
let xaxis:XAxis = XAxis()
barChartView.noDataText = "You need to provide data for the chart."
var dataEntries: [BarChartDataEntry] = []
for i in 0..<dataPoints.count
{
let dataEntry = BarChartDataEntry(x: Double(i), y: values[i])
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(values: dataEntries, label: "موجودی")
let chartData = BarChartData(dataSet: chartDataSet)
xaxis.valueFormatter = formatter
barChartView.xAxis.labelPosition = .bottom
barChartView.xAxis.drawGridLinesEnabled = false
barChartView.xAxis.valueFormatter = xaxis.valueFormatter
barChartView.chartDescription?.enabled = false
barChartView.legend.enabled = true
barChartView.rightAxis.enabled = false
barChartView.data = chartData
}
and finally the formatter:
#objc(BarChartFormatter)
public class BarChartFormatter: NSObject, IAxisValueFormatter
{
var names = [String]()
public func stringForValue(_ value: Double, axis: AxisBase?) -> String
{
return names[Int(value)]
}
public func setValues(values: [String])
{
self.names = values
}
}
but it didn't work well as shown below:
as shown here, it add 6 labels instead 4 labels, and it also has duplicates.
I already read this solution, however, as you can see, it has some issues yet.
How can I solve this problem?
I think you can try to set the following properties:
barChartView.xAxis.granularityEnabled = true
barChartView.xAxis.granularity = 1.0 //default granularity is 1.0, but it is better to be explicit
barChartView.xAxis.decimals = 0
The source code tells you a lot about the properties above. https://github.com/danielgindi/Charts/blob/master/Source/Charts/Components/AxisBase.swift

iOS Charts - Grouped Bar chart not index properly

I'm populating a Combined Chart having a Line Chart and a Grouped Bar Chart BUT
the bars are not coming up as expected. They're not in sync with xAxis indexes. Any help will be appreciated.
Combined Chart Image: Line + Grouped Bar
For the image I've attached, bars should be in sync with each month but they are not.
Here's the code:
private func setLineChartWith(data: [Double]) {
var lineChartEntries: [ChartDataEntry] = []
for i in 0..<data.count {
let lineChartEntry = ChartDataEntry(value: data[i], xIndex: i)
lineChartEntries.append(lineChartEntry)
}
let lineDataSet = LineChartDataSet(yVals: lineChartEntries, label: "Line")
lineDataSet.lineWidth = 3
lineDataSet.circleRadius = 4
lineDataSet.mode = .CubicBezier
lineDataSet.highlightEnabled = true
let lineChartData = LineChartData(xVals: datesData, dataSets: [lineDataSet])
chartData.lineData = lineChartData
}
// MARK: Bar Chart Code
func setBarChartWith(data: [Double], secondaryData: [Double]?) {
var barChartEntries1: [BarChartDataEntry] = []
var barChartEntries2: [BarChartDataEntry] = []
for i in 0..<data.count {
barChartEntries1.append(BarChartDataEntry(value: data[i], xIndex: i))
barChartEntries2.append(BarChartDataEntry(value: data[i], xIndex: i))
}
let barDataSet = BarChartDataSet(yVals: barChartEntries1, label: "Bar1")
barDataSet.barSpace = 0.5
barDataSet.highlightEnabled = true
barDataSet.barShadowColor = UIColor.clearColor()
let barDataSet2 = BarChartDataSet(yVals: barChartEntries1, label: "Bar2")
barDataSet2.barSpace = 0.5
barDataSet2.highlightEnabled = true
barDataSet2.barShadowColor = UIColor.clearColor()
var dataSets : [BarChartDataSet] = [BarChartDataSet]()
dataSets.append(barDataSet)
dataSets.append(barDataSet2)
let barChartData = BarChartData(xVals: datesData, dataSets: dataSets)
chartData.barData = barChartData
}
Probably you are using a library to create your graphic. This bibliotca have this problem, the items are limited in the x-axis. The graph divides them so that the User can understand even without some data. You will realize that it always starts on the first index and ends on the last index of the array so it takes some data from the middle of the x-axis. Thus the User can understand the graph and the graph is not overloaded. There is no right solution in the library for this but you can try to zoom the graph or the labels on the x axis. Increasing the width of the graph should also help.
set those in class level
var barCartDataSet : [IChartDataSet] = []
var colNamesArray : [String]!
//call this function as many time as you needed means how much bars you need in one group
setChartData("Test Lable", values: [2.0,3.0] , color: UIColor.darkGrayColor())
//After that at last call this
setChartDataSet(colNamesArray, chartDataSet: barCartDataSet)
//Functios
func setChartData(lableName: String, values: [Double] , color : UIColor) {
var dataEntries: [BarChartDataEntry] = []
for i in 0..<values.count {
let dataEntry = BarChartDataEntry(value: values[i], xIndex: i)
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(yVals: dataEntries, label: lableName)
barCartDataSet.append(chartDataSet)
//changing color
chartDataSet.colors = [color]
}
func setChartDataSet(dataPoints: [String], chartDataSet : [IChartDataSet]) {
BarChartDrawingView.noDataText = "You need to provide data for the chart."
let chartData = BarChartData(xVals: dataPoints, dataSets: chartDataSet)
chartData.groupSpace = 0.8
BarChartDrawingView.data = chartData
BarChartDrawingView.xAxis.labelPosition = .Bottom
//Description Text
BarChartDrawingView.descriptionText = " "
}
sorry for bad English. Hope it helps :)

Resources