0

I was using the code below to set an HKQueryAnchor when making a HKAnchoredObjectQuery however 'unarchiveObject(with:)' has been deprecated and I can't figure out how to write it with the new API?

private func getAnchor() -> HKQueryAnchor? {
        let encoded = UserDefaults.standard.data(forKey: AnchorKey)
        if(encoded == nil){
            return nil
        }
        
        let anchor = NSKeyedUnarchiver.unarchiveObject(with: encoded!) as? HKQueryAnchor
        return anchor
    }
    
    private func saveAnchor(anchor : HKQueryAnchor) {
        let encoded = NSKeyedArchiver.archivedData(withRootObject: anchor)
        defaults.setValue(encoded, forKey: AnchorKey)
        defaults.synchronize()
    }
GarySabo
  • 5,806
  • 5
  • 49
  • 124

2 Answers2

2

This is what I came up with based on Martin R's link, look ok?

 private func getAnchor() -> HKQueryAnchor? {
    
       

 let encoded = UserDefaults.standard.data(forKey: AnchorKey)
    
    guard let unwrappedEncoded = encoded else { return nil }
    
    guard let anchor = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(unwrappedEncoded as Data) as? HKQueryAnchor
    else {
        return nil
    }
    
    return anchor
}

private func saveAnchor(anchor : HKQueryAnchor) {
    
    do {
        let encoded = try NSKeyedArchiver.archivedData(withRootObject: anchor, requiringSecureCoding: false)
        defaults.setValue(encoded, forKey: AnchorKey)
        defaults.synchronize()
    } catch {
        return
    }
}
GarySabo
  • 5,806
  • 5
  • 49
  • 124
0

Try using JSONDecoder and JSONEncoder to get the data to and from HKQueryAnchor instance, i.e.

private func getAnchor() -> HKQueryAnchor? {
    guard let encoded = UserDefaults.standard.data(forKey: AnchorKey) else {
        return nil
    }

    let anchor = try? JSONDecoder().decode(HKQueryAnchor.self, from: encoded)
    return anchor
}

private func saveAnchor(anchor : HKQueryAnchor) {
    if let encoded = try? JSONEncoder().encode(anchor) {
        defaults.setValue(encoded, forKey: AnchorKey)
        defaults.synchronize()
    }
}
PGDev
  • 23,751
  • 6
  • 34
  • 88