本文介绍了如何使NSAttributedString可编码兼容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在通过JSON进行通讯的主应用程序上构建应用程序扩展。主题和数据位于JSON中,并通过Apple的可编码协议进行解析。我现在遇到的问题是使NSAttributedString可编码兼容。我知道它不是内置的,但我知道它可以转换为数据并返回到。

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 parsed via the codable protocol from Apple. The problem I am experiencing right now is making NSAttributedString codable compliant. I know it is not build in but I know it can be converted to data and back to an nsattributedstring.

投射一个NSAttributedString

Cast a NSAttributedString to data in order to share it via a JSON.

if let attributedText = something.attributedText {
    do {
        let htmlData = try attributedText.data(from: NSRange(location: 0, length: attributedText.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType])
        let htmlString = String(data: htmlData, encoding: .utf8) ?? ""
    } catch {
        print(error)
    }
}

将html JSON字符串转换回NSAttributedString:

Cast a html JSON string back to NSAttributedString:

do {
    return try NSAttributedString(data: self, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
    print("error:", error)
    return  nil
}



我的问题?



My Question?

结构示例(无需考虑可编码的合规性):

Example of the struct (without thinking about codable compliance):

struct attributedTitle: Codable {
    var title: NSAttributedString

    enum CodingKeys: String, CodingKey {
        case title
    }

    public func encode(to encoder: Encoder) throws {}
    public init(from decoder: Decoder) throws {}
}


推荐答案

NSAttributedString 符合 NSCoding ,因此您可以使用 NSKeyedArchiver 来获取 Data 对象。

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

这篇关于如何使NSAttributedString可编码兼容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:47