简体   繁体   English

等待异步操作在Swift中完成

[英]Wait async operation to complete in Swift

I'm processing a lot of data in one ViewController using Alamofire like this : 我正在使用Alamofire在一个ViewController中处理大量数据,如下所示:

Alamofire.request(.GET, APIENDPOINT)
        .responseJSON { (_, _, jsondata, _) in
            // whole lotta json parsing and creating custom objects from json
    }

Essentialy, data is grabbed in one view controller which acts as loading screen that notifies user that something is going on in the background. 本质上,数据被捕获在一个视图控制器中,该控制器充当加载屏幕,通知用户背景中发生了某些事情。 Then when async request complete and all data is populated, data is shown in another view controller. 然后,当异步请求完成并且所有数据都已填充时,数据将显示在另一个视图控制器中。

What is the best way to achieve such behaviour? 实现这种行为的最佳方法是什么?

Do it such that the viewcontroller which sends the request waits until the data has been loaded and parsed into some useful model components. 做到这一点,以便发送请求的ViewController一直等到数据已加载并解析为一些有用的模型组件。 Then, initialize another viewcontroller, pass the parsed data from remote and then show/push it. 然后,初始化另一个viewcontroller,从远程传递解析后的数据,然后显示/推送。

Alamofire.request(.GET, APIENDPOINT)
  .responseJSON { (_, _, jsondata, _) in
    // whole lotta json parsing and creating custom objects from json
  let anotherViewController = AnotherViewController()
  anotherViewController.dataFromRemote = parsedRemoteData
  self.showViewController(anotherViewController, animated:true)
}

Well, I would use a manual segue. 好吧,我会使用手动segue。 Something like this: 像这样:

Alamofire.request(.GET, APIENDPOINT)
    .responseJSON { (_, _, jsondata, _) in
        // whole lotta json parsing and creating custom objects from json
        self.performSegueWithIdentifier("realViewController", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
  if segue.identifier == "realViewController" {
    let vc:MyViewController = segue!.destinationViewController as MyViewController
    vc.setupWithData(self.myParsedData)
  }
}

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

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