为什么我需要按两次此按钮才能显示数据?

时间:2018-01-20 05:16:24

标签: ios xcode swift3 swift4

我不明白为什么我需要按两次按钮才能让标签填满收集的数据。我不确定我是否对json解析做错了,或者是否存在某种范围问题。我确定这里有冗余代码,但我正在尝试我能想到的一切,并通过谷歌找到。

import UIKit

struct SkillStats {
var Rank, Level, Experience: String
init(Rank: String = "", Level: String = "", Experience: String = "") {
    self.Rank = Rank
    self.Level = Level
    self.Experience = Experience
    }
}

var rsn: String = ""

class ViewController: UIViewController {
  var Total = SkillStats()

@IBOutlet weak var totalXP: UILabel!
@IBOutlet weak var totalLevel: UILabel!
@IBOutlet weak var totalRank: UILabel!

@IBOutlet weak var getrsn: UITextField!
@IBAction func rsnButton(_ sender: Any) {
rsn = getrsn.text!

rsn = rsn.replacingOccurrences(of: " ", with: "%20")
rsn = rsn.replacingOccurrences(of: "-", with: "%2D")

print(rsn)

//let rsn = "Real%20Nice"
 let jsonUrlString = "http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player=" + rsn
 guard let url = URL(string: jsonUrlString) else
 {return}

 URLSession.shared.dataTask(with: url) { (data, repsonse, err) in

 guard let data = data else {return}

 let dataAsString = String(data: data, encoding: .utf8)
 //print(dataAsString)

 let result = dataAsString?.components(separatedBy: [",","\n"])

 //comment this block
 //Total.Rank = result![0]
 //Total.Level = result![1]
 //Total.Experience = result![2]


  self.Total = SkillStats(Rank: result![0], Level: result![1], Experience: result![2])

 //printing stats to console
  print("Total Rank: " + self.Total.Rank)
  print("Total Level: " + self.Total.Level)
  print("Total Experience: " + self.Total.Experience)
 }.resume()

totalRank.text = "Rank: " + Total.Rank
totalLevel.text = "Level: " + Total.Level
totalXP.text = "XP: " + Total.Experience
}

1 个答案:

答案 0 :(得分:0)

按一下按钮,等待新的秒数,因为您正在进行api通话,从服务器获取数据并更新标签文本需要一些时间。

<强>更新

要在几秒钟后更新标签,您可以执行以下操作:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {

            self.totalRank.text = "Rank: " + self.Total.Rank
            self.totalLevel.text = "Level: " + self.self.Total.Level
            self.totalXP.text = "XP: " + self.Total.Experience
        }
  

PS - 是的,你可以传递第二个值小于1的代码。