TK-421 TK-421 - 4 years ago 129
Swift Question

How to use imported HealthKit samples in other classes

I have imported all the necessary health data into my app, but when I try to use the health variables outside of the class in which I imported them, I keep getting

nil
values.

I have a class with a method that successfully imports the data and a method that successfully prints the data:

class HealthData:NSObject {

var healthData:Double?

func importData() {
readMostRecentSample(sampleType!, completion: { (mostRecentSample, error) -> Void in
self.printData()
})
}
func printData() {
print(healthData)
}
}


But when I try and do something like this in a new class:

class HealthAlgorithm:NSObject {

var healthData2 = HealthData().healthData

func printData() {
print(healthData2)
}
}


And I call that function from the same place I successfully called the original
printData
method:

class HealthData:NSObject {

var healthData:Double?

func importData() {
self.printsData()
HealthAlgorithm().printsData()
}
func printsData() {
print(healthData)
}
}


I've run into issues similar to this, and I realize that the method querying for HealthKit samples completes asynchronously, but I'm a little stumped as to exactly what is happening here. I think I'm missing something to do with completion handlers, but I'm not sure exactly where to start.

(If you want more complete code, I can include it, but I thought I would save some space by simplifying things.)

Answer Source

This is not a healthKit problem.

In all your classes

 var healthData:Double?

is an instance variable that is automatically initialized with nil. This means in

var healthData2 = HealthData().healthData

the part

HealthData()

creates a new instance. So

HealthData().healthData

is always nil, since you didn't import anything in this instance.

You probably imported into another instance of that class.

More about this: Apples Swift eBook is free.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download