【问题标题】:How to get around 'unarchiveObject(with:)' was deprecated in iOS 12.0 when setting an HKQueryAnchor?设置 HKQueryAnchor 时,如何绕过 iOS 12.0 中已弃用的“unarchiveObject(with:)”?
【发布时间】:2021-01-03 09:09:36
【问题描述】:

我在创建HKAnchoredObjectQuery 时使用下面的代码设置HKQueryAnchor,但是'unarchiveObject(with:)' 已被弃用,我不知道如何使用新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()
    }

【问题讨论】:

标签: ios swift healthkit nskeyedarchiver


【解决方案1】:

尝试使用 JSONDecoderJSONEncoderdataHKQueryAnchor 实例联系起来,即

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()
    }
}

【讨论】:

  • 我认为要使其正常工作,您需要扩展 HKQueryAnchor 以符合 Decodable
【解决方案2】:

这是我根据 Martin R 的链接想出的,看起来好吗?

 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
    }
}

【讨论】:

    猜你喜欢
    • 2020-04-18
    • 2020-08-23
    • 2019-05-03
    • 2019-04-05
    • 1970-01-01
    • 2022-01-12
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多