J'ai les méthodes updateHeight
, updateWeight
et updateBMI
dans ma classe HealthAlgorithm
. J'essaie ensuite de les appeler pour en ViewController.swift
Méthodes de déclenchement dans le désordre
HealthAlgorithm.swift
:
//MARK: Properties
var healthManager:HealthManager?
var kUnknownString = "Unknown"
var bmi:Double?
var height:HKQuantitySample?
var weight:HKQuantitySample?
func updateHeight() {
// 1. Construct an HKSampleType for weight
let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)
// 2. Call the method to read the most recent weight sample
HealthManager().readMostRecentSample(sampleType!, completion: { (mostRecentHeight, error) -> Void in
if(error != nil)
{
print("Error reading height from HealthKit Store: \(error.localizedDescription)")
return
}
var heightLocalizedString = self.kUnknownString
self.height = mostRecentHeight as? HKQuantitySample
print(self.height)
// 3. Format the height to display it on the screen
if let meters = self.height?.quantity.doubleValueForUnit(HKUnit.meterUnit()) {
let heightFormatter = NSLengthFormatter()
heightFormatter.forPersonHeightUse = true
heightLocalizedString = heightFormatter.stringFromMeters(meters)
}
})
}
func updateBMI(){
if weight != nil && height != nil {
// 1. Get the weight and height values from the samples read from HealthKit
let weightInKilograms = weight!.quantity.doubleValueForUnit(HKUnit.gramUnitWithMetricPrefix(.Kilo))
let heightInMeters = height!.quantity.doubleValueForUnit(HKUnit.meterUnit())
bmi = (weightInKilograms/(heightInMeters * heightInMeters))
}
print("BMI: ",bmi)
}
J'appelle ces méthodes ViewController.swift
comme ceci:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
HealthAlgorithm().updateHeight()
HealthAlgorithm().updateWeight()
HealthAlgorithm().updateBMI()
}
Le problème est que l'IMC est retourné comme nil
. La raison pour laquelle cela se produit est que la méthode updateBMI
tire avant la méthode updateHeight
et updateWeight
.
J'utilise print(self.height)
juste après avoir définir la variable dans la méthode updateHeight
, et j'utilise print("BMI: ", bmi)
juste après avoir définir la variable IMC dans le procédé updateBMI
. Comme j'appelle updateHeight
d'abord, print(self.height)
devrait se produire avant print("BMI: ", bmi)
, mais pour une raison quelconque, le BMI: nil
est retourné en premier, ce qui n'a aucun sens pour moi.
Les méthodes ne sont pas appelées dans le désordre. Le problème est que la fonction se termine de manière asynchrone. Vous devez appeler le code dépendant du gestionnaire de complétion –
La fonction 'updateBMI' est appelée alors que' updateHeight' est toujours en cours d'exécution? – 123
'updateHeight' renvoie avant que le gestionnaire d'achèvement soit appelé, donc la réponse est" presque définitivement ". –