I have a function which grabs a couple variables from an online JSON, one of those being the Approved variable which is set to "true"
. When I call the function, the first time I will get the "Denied" alert since the Approved variable does not have a value since the code is not asynchronous, but no matter what I do I can't get it to work. It's only until the second time that it has the previous value saved and goes to the Success alert.
The code:
@IBAction func approveuser(_ sender: AnyObject) {
theplace = place //Saving variable.
Alamofire.request("https://example.com?variable=\(variable)&requested=\(self.place)").responseJSON{ response in
if let JSON = response.result.value{
let json = JSON as! NSDictionary
Approved = json["Approved"] as! String
LoadedVersion = json["version"] as! String
}
}
if(AppVersion != LoadedVersion){
self.showalert("Update Required", message: "Please update the app", confirm: "Okay")
return
}
if(Approved == "true"){
self.showalert("Approved!", message: "Success", confirm: "Okay")
}else{
self.showalert("Denied!", message: "Denied", confirm: "Okay")
}
}
I have tried placing DispatchQueue.main.async {
wherever I can in the code but it still does not want to work no matter where I put it.
Where put the codes for asynchronous on main queue?
I think like below be work as your intended.
@IBAction func approveuser(_ sender: AnyObject) {
theplace = place //Saving variable.
Alamofire.request("https://example.com?variable=\(variable)&requested=\(self.place)").responseJSON{ response in
if let JSON = response.result.value{
let json = JSON as! NSDictionary
Approved = json["Approved"] as! String
LoadedVersion = json["version"] as! String
}
DispatchQueue.main.async {
if(AppVersion != LoadedVersion){
self.showalert("Update Required", message: "Please update the app", confirm: "Okay")
return
}
if(Approved == "true"){
self.showalert("Approved!", message: "Success", confirm: "Okay")
}else{
self.showalert("Denied!", message: "Denied", confirm: "Okay")
}
}
}
}