How to make NSAttributedString codable compliant?

前端 未结 1 1679
北荒
北荒 2021-01-06 09:27

What is the problem?

Currently I am building an app-extension on my main app which communicates via a JSON. Theming and data is located in the JSON and is being pa

相关标签:
1条回答
  • NSAttributedString conforms to NSCoding so you can use NSKeyedArchiver to get a Data object.

    This is a possible solution

    class AttributedString : Codable {
    
        let attributedString : NSAttributedString
    
        init(nsAttributedString : NSAttributedString) {
            self.attributedString = nsAttributedString
        }
    
        public required init(from decoder: Decoder) throws {
            let singleContainer = try decoder.singleValueContainer()
            guard let attributedString = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(singleContainer.decode(Data.self)) as? NSAttributedString else {
                throw DecodingError.dataCorruptedError(in: singleContainer, debugDescription: "Data is corrupted")
            }
            self.attributedString = attributedString
        }
    
        public func encode(to encoder: Encoder) throws {
            var singleContainer = encoder.singleValueContainer()
            try singleContainer.encode(NSKeyedArchiver.archivedData(withRootObject: attributedString, requiringSecureCoding: false))
        }
    }
    
    0 讨论(0)
提交回复
热议问题