I am trying to load data from Server, through Alamofire
, before SubViewController Load its view. After writing the code, I failed to solve the problem of Async Feature of Alamofire. The view is always be loaded in the SubViewController before Alamofire finished its job.
ParentViewController:
Leading the way to SubViewController through PrepareForSegue()
.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "CellDetailSegue" {
if let indexPaths = self.dateCollectionView.indexPathsForSelectedItems() {
let subViewController = segue.destinationViewController as! SubViewConroller
}
}
SubViewController:
Test whether the data has been loaded by print()
in the its viewDidLoad()
and load the data by dataRequest()
in viewWillAppear()
class SubViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var availablePeriods401 = [String]()
var availablePeriods403 = [String]()
var availablePeriods405 = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.dataRequest(self.availablePeriods401)
self.dataRequest(self.availablePeriods403)
self.dataRequest(self.availablePeriods405)
print(self.availablePeriods401.count)
print(self.availablePeriods403.count)
print(self.availablePeriods405.count)
}
func dataRequest(_ target: [String]) {
Alamofire.request(.POST, "http://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON {
.
.
.
target = Result
}
}
}
Three variables in the SubViewController can not be assigned the valid values after view was loaded.
Three Outputs' results are all 0.
But I can get valid count if I set print()
in the dataRequest()
.
How to make sure that Alamofire
finishes its job?
Where Shall I put the Alamofire Request Function? viewWillApper()
? viewDidApper()
?
Should I even finished requesting job in ParentViewController's PrepareForSegue()
?
Please teach me how to solve this problem.
A big appreciation for your guide and time.
Ethan Joe
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…