KeykoYume KeykoYume - 3 months ago 21
Swift Question

Function not executed when it is called

I have the following basic code structure:

self.ok_today = 0
checkToday("Daily Steps")
if (self.ok_today == 0) {}


My problem is that the actions are not executed in order. When I run it, my variable is initialised to 0, then it executes the
if
block and after that the
checkToday()
method. (and since my variable is never incremented it always goes to the if block)

This the checkToday method, that uses Alamofire to fetch some data:

func checkToday(concept: String) {

let user = "***"
let password = "***"

let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])

let headers = ["Authorization": "Basic \(base64Credentials)"]

Alamofire
.request(.GET, "http://***/ws/fhir/Observation?date="+self.todayStepsDate+"T00:00:00", headers: headers)
.responseJSON { response in
var json = JSON(response.result.value!)
var i = 0
while (json["entry"][i]["resource"]["valueQuantity"]["value"] != nil) {

// Checks if the user synced his data for current day
if (json["entry"][i]["resource"]["code"]["coding"][0]["display"].rawString() == concept){
let patientAux: String = "Patient/"+self.person_uuid
if (json["entry"][i]["resource"]["subject"]["reference"].rawString() == patientAux){
self.ok_today = self.ok_today+1
}
}
i=i+1
}
}
}


Any idea why I might have this problem?

Answer

The Alamofire requests are asynchronous. You should work with callbacks. Change your code to this to get the desired functionality.

func checkToday(concept: String, callback: () -> ()) {

        let user = "***"
        let password = "***"

        let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
        let base64Credentials = credentialData.base64EncodedStringWithOptions([])

        let headers = ["Authorization": "Basic \(base64Credentials)"]

       Alamofire
        .request(.GET, "http://***/ws/fhir/Observation?date="+self.todayStepsDate+"T00:00:00", headers: headers)
        .responseJSON { response in
            var json = JSON(response.result.value!)
            var i = 0
            while (json["entry"][i]["resource"]["valueQuantity"]["value"] != nil) {

                // Checks if the user synced his data for current day
                if (json["entry"][i]["resource"]["code"]["coding"][0]["display"].rawString() == concept){
                    let patientAux: String = "Patient/"+self.person_uuid
                    if (json["entry"][i]["resource"]["subject"]["reference"].rawString() == patientAux){
                        self.ok_today = self.ok_today+1
                    }
                }
                i=i+1
            }
            //code is done, now call the callback
            callback()
        }
    }

And use it like this

self.ok_today = 0
checkToday("Daily Steps") {
    //callback is called
    if (self.ok_today == 0) {}
}