无法将对象附加到闭包内的数组

时间:2019-09-29 11:58:43

标签: ios swift api

我是新手,我想到了构建一个可以显示实时现场比分的应用的想法。 因此,我使用Alamofire框架通过闭包发出HTTP请求。

为了表示每个单独的比赛分数和结果,我创建了一个名为“得分”的以下类:

class Score {

var homeTeamName : String = ""
var visitorTeamName : String = ""
var matchScore : String = ""
var matchTime : String = ""}

在LiveScoresViewController中,我声明并初始化了一个全球空集合,类型为“ Scores”,将在其中存储实时比分

var scoresArray : [Score] = [Score]()

然后我创建两个方法:

  • getLiveScore:发出http请求
func getLiveScores(url : String) {
        Alamofire.request(url, method: .get).responseJSON { response in

            if response.result.isFailure {
                let alert = UIAlertController(title: "Error Occured", message: "Please check your connection or restart the application", preferredStyle: UIAlertController.Style.alert)
                let alertAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.cancel)

                alert.addAction(alertAction)
            }

            else {
                let liveScoresJSON : JSON = JSON(response.result.value!)
                self.updateLiveScore(json: liveScoresJSON)
            }
        }
    }
  • updateLiveScore:解析并表示JSON结果
func updateLiveScore(json : JSON) {
        let size = json["result"].count

        for index in 0..<size {
            let match = Score()
            match.homeTeamName = json["result"][index]["event_home_team"].string!
            match.visitorTeamName = json["result"][index]["event_away_team"].string!
            match.matchScore = json["result"][index]["event_final_result"].string!
            match.matchTime = json["result"][index]["event_status"].string!

            scoresArray.append(match)
        }
    }
在viewDidLoad()函数中调用了

getLiveScore方法,但是即使请求结果不正确,“ scoresArray”仍为空!我试图在方法的参数中传递集合,但是我意识到我不能迅速修改它,而且不像Java,参数是常量。

1 个答案:

答案 0 :(得分:0)

首先,最好使用Codable来解码响应

第二对api的调用是异步的,这就是为什么它在viewDidLoad中为空的原因,因此,在将数据附加到数组之后,您需要刷新闭包内部的表/集合