我有以下基本代码结构:
self.ok_today = 0
checkToday("Daily Steps")
if (self.ok_today == 0) {}
我的问题是这些操作没有按顺序执行。当我运行它时,我的变量初始化为0,然后执行if
块,然后执行checkToday()
方法。 (因为我的变量永远不会增加,所以它总是转到if块)
这是checkToday方法,它使用Alamofire获取一些数据:
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
}
}
}
知道为什么我会遇到这个问题吗?
答案 0 :(得分:1)
Alamofire请求是异步的。你应该使用回调。将代码更改为此以获得所需的功能。
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()
}
}
并像这样使用
self.ok_today = 0
checkToday("Daily Steps") {
//callback is called
if (self.ok_today == 0) {}
}