简体   繁体   English

无法将数据传递给viewdidload,Swift

[英]can not pass data to viewdidload, Swift

i requested data from webserver by alamofire. 我通过alamofire向Web服务器请求了数据。 i want to pass data to viewdidload but data in viewdidload is empty, please help me explain. 我想将数据传递给viewdidload,但viewdidload中的数据为空,请帮助我解释一下。 thanks and sory for my english. 谢谢你,谢谢我的英语。 this my code 这是我的代码

class LiveScoreViewController: UIViewController 
{
   var matchData : JSON! = []

func loadLiveScore(section: String){
    DNService.getLiveScore(section) { (JSON) -> () in
        self.matchData = JSON[ ]

        self.matchData = self.matchData["match"]
        //print(self.matchData) -> is ok
    }
}


override func viewDidLoad() {
    super.viewDidLoad()

    loadLiveScore("LiveScore")

    //print(self.matchData) -> is empty 

}}

If DNService.getLiveScore is a webservice call, then you wont be able to get the matchData inside viewDidLoad, since the webservice call will take some time to complete, whatever you are trying to do with the matchData should be done in the completion block of DNService.getLiveScore most likely 如果DNService.getLiveScore是一个Web服务调用,那么您将无法在viewDidLoad中获取matchData,因为该Web服务调用将需要一些时间才能完成,因此您尝试对matchData进行的操作都应在DNService的完成代码块中DNService.getLiveScore最有可能

If you want, you can put a print statement right after loadLiveScore in viewDidLoad and also in the completion block, and you will see the order of execution of the print statements is not what you are expecting 如果需要,可以将打印语句放在loadLiveScore之后的viewDidLoad ,也可以放在完成块中,并且您会看到打印语句的执行顺序与预期不符

getLiveScore is asynchronous method. getLiveScore是异步方法。 So you have to use completion handler to get the response. 因此,您必须使用完成处理程序来获取响应。 Make an handler for loadLiveScore loadLiveScore创建处理程序

func loadLiveScore(section: String), handler: (JSON) -> ()) {

    DNService.getLiveScore(section) { (JSON) -> () in

        handler(JSON) 

    }
}

Call the method from your viewDidLoad as like: 从您的viewDidLoad调用方法,如下所示:

override func viewDidLoad() {
    super.viewDidLoad()

    loadLiveScore("LiveScore") { json in

        print(json) // parse JSON as you need

        self.matchData = json["match"]
    }
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM