I want my function openDoor to return true, if the API call has given us doorStatus "OPENED" However, I run into a problem, where this function returns before the API call has been made, making it return false every time, because it has been initialised so. My question is how do I make api request first, so that I can assign doorStatusL true or false based on that API call to return it at the end?
func openDoor(requesto: URLRequest) ->Bool {
var doorstatusL = false;
func sendRequest() -> Bool {
NSURLConnection.sendAsynchronousRequest(requesto, queue: OperationQueue.main) {(response, data, error) in
guard let data = data else {
return
}
print(String(data: data, encoding: .utf8)!)
do {
let json = try JSONDecoder().decode([WelcomeElement].self, from: data )
//try JSONSerialization.jsonObject(with: data!, options: [])
print(json[0].doorstatus)
if(json[0].doorstatus == "OPENED"){
doorstatusL = true;
print(doorstatusL)
print("assigned TRUE")
}
} catch {
print("Status Error during JSON serialization: \(error.localizedDescription)")
}
}
return true
}
if(sendRequest()==true){
print(doorstatusL)
print("=======+++++++")
return doorstatusL
} else {
print("returned false at the end")
return false
}
return true;
}
Output from a terminal is
false
=======+++++++
[{"message":"OPEN, ENTER ","doorstatus":"OPENED"}]
OPENED
true
assigned TRUE
Thank you
SOLVED
func sendRequest(requesto: URLRequest, success:Bool, completionHandler: @escaping (Bool)->Void) {
var doorStatusL = false
NSURLConnection.sendAsynchronousRequest(requesto, queue: OperationQueue.main) { (response, data, error) in
guard let data = data else { return }
do {
let json = try JSONDecoder().decode([WelcomeElement].self, from: data )
if(json[0].doorstatus == "OPENED") {
doorStatusL = true
completionHandler(doorStatusL)
}
} catch {
print("Status Error during JSON serialization: \(error.localizedDescription)")
}
}
}
let completionhandler:(Bool)->Void = { (success) in
if success {
sendNotifications()
}
}
sendRequest(requesto: request2, success: true, completionHandler: completionhandler)