我正在尝试使用iOS图表创建我的第一个实时图表,并从我的数据库中提取数据。
我数据库中的数据包括赢取,抽取,丢失的游戏。这些是整数(但iOS图表要求它们是双打,但这是另一个问题)。
我的主要问题是图表没有使用我的数据进行更新 - 如果我在行中手动输入数据,let games = [4.0, 8.0, 2.0]
,它就可以正常工作。但是从数据库中提取数据我得不到任何结果。
import UIKit
import Charts
class ShowCommunityViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//********CHART VARIABLES**************//
var totalWins: Double = 0.0
var totalDraws: Double = 0.0
var totalLosses: Double = 0.0
//**************************************
override func viewDidLoad() {
results = ["Won", "Drawn", "Lost"]
let games = [totalWins, totalDraws, totalLosses]
setChart(dataPoints: results, values: games)
}
// ******* CHARTS FUNCTIONS ************
func setChart(dataPoints: [String], values: [Double]){
barChartView.noDataText = "you need to provide some data for the chart."
var dataEntries: [BarChartDataEntry] = Array()
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(x: Double(i), y: values[i])
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(values: dataEntries, label: "Games Played")
let chartData = BarChartData()
self.barChartView.xAxis.labelPosition = XAxis.LabelPosition.bottom
barChartView.leftAxis.granularityEnabled = true
barChartView.rightAxis.enabled = false
barChartView.leftAxis.granularity = 1.0
chartData.addDataSet(chartDataSet)
barChartView.data = chartData
}
// ********* API CALL *****
override func viewDidAppear(_ animated: Bool) {
let defaults = UserDefaults.standard
let playerId = defaults.string(forKey: "playerId")
let email = defaults.string(forKey: "userEmail")
self.personalSelf = true
let myUrl = URL(string: "http://www.xxx.uk/xxx/xxx.php?");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "community_id=\(comIds[communityId!])&player_id=\(playerId!)&email=\(email!)";
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
{
if error != nil {
print("error=\(error)")
return
}
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
print (json!)
if let dict = json?["Stats"] as? [String:AnyObject] {
if let total_Wins = dict["totalWins"] as? Double,
let total_Draws = dict["totalDraws"] as? Double,
let total_Losses = dict ["totalLosses"] as? Double{
self.totalWins = total_Wins
self.totalDraws = total_Draws
self.totalLosses = total_Losses
}
} catch{
print(error)
}
}
}
task.resume()
}
我的问题是图表没有更新。我猜这是因为在提取数据之前显示图表?
....在旁注中,我希望显示Int
而不是Floats
,但它要求所有内容都是double
我哪里错了?
更新:
解决方案工作 - 显示浮动而不是Ints和图表底部缺少标签,显示数字而不是&#34;赢得&#34;,&#34;绘制&#34;,&#34;丢失&#34 ;
答案 0 :(得分:0)
self.totalWins = total_Wins
self.totalDraws = total_Draws
self.totalLosses = total_Losses
//在您的回复中添加此行
results = ["Won", "Drawn", "Lost"]
let games = [total_Wins, total_Draws, total_Losses]
setChart(dataPoints: results, values: games)
检查输出。