Any way to get Int value of HKQueryAnchor?

Beta 5 added the

HKQueryAnchor
class, which includes a convenience initializer
HKQueryAnchor.init(fromValue: Int)
.


Prior to beta 5, the anchor was represented as an

Int
. This made it possible to persist the anchor as an
Int
.


In beta 5, while I can construct a new HKQueryAnchor from an

Int
, I cannot get the
Int
representation of the
HKQueryAnchor
.


Is there any way to get the

Int
value of an
HKQueryAnchor
?

Accepted Reply

HKQueryAnchor implements NSSecureCoding, so it should be possible to persist this as NSData via a call to NSKeyedArchiver.archivedDataWithRootObject and then using a NSKeyedUnarchiver instance on which you would call decodeObjectOfClass. The problem that I've experienced is that the result from an unarchive call does not appear to be equal to the original value.

Replies

I would also like to know how to use the new HKQueryAnchor object? Should we persist it somehow or is there another option for retrieving data without persisting it?

HKQueryAnchor(fromValue: Int(HKAnchoredObjectQueryNoAnchor))

Did anyone manage to solve how to persist this?

HKQueryAnchor implements NSSecureCoding, so it should be possible to persist this as NSData via a call to NSKeyedArchiver.archivedDataWithRootObject and then using a NSKeyedUnarchiver instance on which you would call decodeObjectOfClass. The problem that I've experienced is that the result from an unarchive call does not appear to be equal to the original value.

This is the way I wound up doing it. I'm saving it in a text file in the documents directory. Not the prettiest solution (I much preferred being able to persist it as an Int, though I'm sure Apple has their reasons for not allowing it), but it works.


For those who are curious, the code I settled on looks like this:

+ (nullable HKQueryAnchor *)hkAnchor {
    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    NSString *filePath = [url.path stringByAppendingPathComponent:@"hkAnchor.txt"];
    HKQueryAnchor *anchor = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    return anchor;
}
+ (void)setHKAnchor:(HKQueryAnchor *)anchor {
    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    NSString *filePath = [url.path stringByAppendingPathComponent:@"hkAnchor.txt"];
    [NSKeyedArchiver archiveRootObject:anchor toFile:filePath];
}


Thanks for the help, and best of luck.

I am also facing the same issue. I want to extract Int value from HKQueryAnchor object and want to send it to the remote server.