I am new to Swift and was wondering how can I get a value from an Async task. I have a function that gets Json data from an API on return I would like to get the value of a particular field outside of the async task... My code is below essentially I have a variable called status I want to get the value of status after the async called is returned then I want to check if the value is 1 . In the code below the value returned is 1 however it seems like the async called is executed before the line if Status == 1 {} . If the value is One then I want to navigate to a different ViewController . Any suggestions would be great ... I obviously can not put the code to go to a different ViewController inside the Async code since that is called many times .
func GetData() {
var status = 0
// Code that simply contains URL and parameters
URLSession.shared.dataTask(with:request, completionHandler: {(data, response, error) in
if error != nil {
print("Error")
} else {
do {
let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
DispatchQueue.main.async {
if let Replies = parsedData["Result"] as? [AnyObject] {
for Stream in Replies {
if let myvalue = Stream["status"] as? Int {
status = myvalue
}
}
}
}
} catch let error as NSError {
print(error)
}
}
}).resume()
if status == 1 {
// This code is executed before the async so I don't get the value
let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "Passed") as! Passed
self.present(nextViewController, animated:false, completion:nil)
}
}