Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Can';t将对象附加到闭包内的数组_Ios_Swift_Api - Fatal编程技术网

Ios Can';t将对象附加到闭包内的数组

Ios Can';t将对象附加到闭包内的数组,ios,swift,api,Ios,Swift,Api,我是swift的新手,我有了构建一个显示实时分数的应用程序的想法。 因此,我使用Alamofire框架通过闭包发出HTTP请求 为了表示每个比赛分数和结果,我创建了以下名为“score”的类: 在LiveScoresViewController中,我声明并初始化了一个类型为“Scores”的全局空集合,其中将存储livescores var scoresArray : [Score] = [Score]() 然后我创建了两种方法: getLiveScore:发出http请求 update

我是swift的新手,我有了构建一个显示实时分数的应用程序的想法。 因此,我使用Alamofire框架通过闭包发出HTTP请求

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

在LiveScoresViewController中,我声明并初始化了一个类型为“Scores”的全局空集合,其中将存储livescores

var scoresArray : [Score] = [Score]()
然后我创建了两种方法:

  • getLiveScore:发出http请求
  • updateLiveScore:解析JSON结果并表示它
func updateLiveScore(json:json){
让size=json[“结果”].count

对于0..中的索引,最好先使用
Codable
对响应进行解码


Second对api的调用是异步的,这就是为什么它在
viewdiload
中是空的,所以在将数据附加到数组后,您需要刷新闭包中的表/集合

您如何知道
scoresArray
是空的?您是否通过调试器查看过它?您是否确保检查过它er是否收到响应?@Sweeper在调用“getLiveScore”方法后,我打印了集合的大小,但它是空的(输出:0)如果您这样调用它,0是预期的输出,因为尚未收到响应。在internet上请求内容需要时间。要获得非零输出,您可以在
scoresArray
didSet
中打印它,或者在调用
updateLiveScore
@Sweeper是之后,集合不为空r我调用updateLiveScore,但我需要在表视图中表示分数,我的问题是我不熟悉闭包,因此闭包中的附加值在它之外不再可用
var scoresArray : [Score] = [Score]()
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)
            }
        }
    }
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)
        }
    }