I am having trouble populating a scene with a list of images. I am using UIViewController and not a tableView to display my interface. Imagine Tinder like application. No tableview. To scroll through the images, each images are being swiped to the next.
The way I populate the images on the scene is by making a POST request inside ViewDidLoad using URLSession.DataTask. But I am having trouble with what seem like a multi threading issues.
Original code:
ViewDidLoad(){
queryService.getProduct { productlist, errorMessage in
if !errorMessage.isEmpty { print("Search error: " + errorMessage) }
self.products = productlist
}
// CODE TO initialize View
// MORE CODE
}
queryService contains URLSession.DataTask which calls the URL and carries out Serialization. That method has been implemented correctly. The problem I am facing is that self.products get instantiated after "CODE TO initialize View" section. They both seem to be running in parallel. So here is what I did to remedy the fix:
Quick fix:
var count = 0
ViewDidLoad(){
if count == 0 {
queryService.getProduct { productlist, errorMessage in
if !errorMessage.isEmpty { print("Search error: " + errorMessage) }
self.products = productlist
self.count = 1
self.ViewDidLoad()
}
} else {
// CODE TO initialize View
// MORE CODE
}
}
This works but I know my quick fix is not the best practice. Any advice on the most optimal solution? Thanks. Also a follow up question: Is it okay to call viewdidload manually like this?
You can do this function but not in `viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
getProductUntilThereIsOneProductAtLeast()
}
func getProductUntilThereIsOneProductAtLeast() {
if count == 0 {
queryService.getProduct { productlist, errorMessage in
if !errorMessage.isEmpty { print("Search error: " + errorMessage) }
self.products = productlist
self.count = 1
self.getProductUntilThereIsOneProductAtLeast()
}
} else {
// CODE TO initialize View
// MORE CODE
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.