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