How to Make Nsattributedstring Codable Compliant

How to make NSAttributedString codable compliant?

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

Update:

In Swift 5.5 native AttributedString has been introduced which conforms to Codable.

Conforming NSAttributedString to Codable throws error

You can try unarchiveTopLevelObjectWithData to unarchive your AttributedString object data:

NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)

Your AttributedString implemented as a struct should look something like this:

struct AttributedString {
let attributedString: NSAttributedString
init(attributedString: NSAttributedString) { self.attributedString = attributedString }
init(string str: String, attributes attrs: [NSAttributedString.Key: Any]? = nil) { attributedString = .init(string: str, attributes: attrs) }
}

Archiving / Encoding

extension NSAttributedString {
func data() throws -> Data { try NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: false) }
}

extension AttributedString: Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(attributedString.data())
}
}

Unarchiving / Decoding

extension Data {
func topLevelObject() throws -> Any? { try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(self) }
func unarchive<T>() throws -> T? { try topLevelObject() as? T }
func attributedString() throws -> NSAttributedString? { try unarchive() }
}

extension AttributedString: Decodable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
guard let attributedString = try container.decode(Data.self).attributedString() else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Corrupted Data")
}
self.attributedString = attributedString
}
}

How To Optimize Storage Of NSAttributedString In Swift Using Data And Codable?

TL;DR: RTFD encodes images as PNGs, but you can make it encode JPGs instead to save space. A custom format might be better and easier though if you have the time to create one.

NSAttributedString can encode to HTML, rtf, rtfd, plain text, a variety of Office/Word formats, etc. Given that each of these is an official format with an official spec that must be followed, there's not much that can be done in terms of saving space other than:

  1. Choosing the supported format that works best for your use cases and has the smallest footprint.

OR


  1. Writing your own format.

Approach 1: RTFD

Of the supported format, RTFD does indeed sound best for your use case because it includes support for attachments such as images. Feel free to try out other included formats, of which descriptions are below in "Other Formats".

Saving it as Data, for example using the rtfd(from:documentAttributes:) method, and as part of a Codable structure, results in a very large string, much larger than the content itself especially when inserting an image into the NSTextView. For example, inserting a 200K image will result in a 5MB JSON file.

To understand what is happening here, try out the following code:

do {
let rtfd = try someAttributedString.rtfdFileWrapper(from: NSRange(location: 0, length: someAttributedString.length), documentAttributes: [:])
rtfd?.write(to: URL(fileURLWithPath: "/Users/yourname/someFolder/RTFD.rtfd"), options: .atomic, originalContentsURL: nil)
} catch {
print("\(error)")
}

When you call rtfd(from:documentAttributes:), you're getting flat Data. This flat data can then be encoded somewhere and read back into NSAttributedString. But make no mistake: RTFD is a package format ("D" stands for directory). So by instead calling rtfdFileWrapper(from:documentAttributes:), and writing that to a URL with the rtfd extension, we can see the actual package format that rtfd(from:documentAttributes:) replicates, but as a directory instead of raw data. In Finder, right click the generated file and choose "Show Package Contents".

The RTFD package contains an RTF file to specify the text and attribitues, and a copy of each attachment. So why was your example so much bigger? In my tests, the answer seems to be that RTFD expects to find its images in PNG format. When calling rtfdFileWrapper(from:documentAttributes:) or rtfd(from:documentAttributes:), any image attachments seem to get written out as PNG files, which take up significantly more space. This happens because your image gets wrapped in a NSImage before getting wrapped in a NSTextAttachment. The NSImage is able to write the image data out in other formats, including larger formats like PNG.

I'm assuming the image you tried was in a compressed format like JPEG, and NSAttributedString wrote it to RTFD as PNG.

Using JPEG instead

Assuming you're okay with the image being compressed and not having info such as an alpha channel, you should be able to create an RTFD file with jpg images.

For example, I was able to get an RTFD file down to 2.8 MB from over 12 MB (large image) just by replacing the generated PNG image with the original JPG one. This initially was unacceptible to TextEdit but I then changed the file extension of the image to .png (even though it is still a JPG) and it accepted it.

In code it was even simpler. You may be able to get away with just changing how you add image attachments.

// Don't do this unless you want PNG
let image = NSImage(contentsOf: ...) // NSImage will write to a larger PNG file
let attachment = NSTextAttachment()
attachment.image = image

// Do this if you want smaller files
let image = try? Data(contentsOf: ...) // This will remain in raw JPG format
let attachment = NSTextAttachment(data: image, ofType: kUTTypeJPEG as String) // Explicitly specify JPG

Then when you create a new NSAttributedString with that NSTextAttachment and append it to NSTextStorage, writing RTFD data will be signifantly smaller.

Of course, you may not have control of this process if you're relying on Cocoa UI/API for attaching images. That could make the process more difficult and you may need to resort to modifying the generated data by swapping images.

Approach 2: Custom Format

The approach described immediately above might be inconvenient due to not having control of the attachment-adding process and needing flat data. In that case a custom format might be better.

There's nothing stopping you from designing your own format (binary, text, package, whatever) and then writing a coder for it. You could specify a specific image format or support a variety. It's up to you. And unless you're a fancy word processor, you probably don't need to store all the attributes like font all the time.

I am also wondering whether there is a valid binary encoding option for Codable.

First, note that NSAttributedString is an Objective-C class (when used on Apple platforms) and conforms to NSSecureCoding instead of Codable.

Note that you cannot extend NSAttributedString to conform to Codable, because the init(from:) requirement on Decodable can only be satisfied by guarenteeing that the initializer will be included on all subclasses as well. Since this class is non-final, that means it can only be satisfied by a required init. Required initializers can only be specified on the original declaration, not extensions.

For this reason, if you wanted to conform it to Codable, you would need to use a wrapper object. enumerateAttributes(in:options:using:) should be helpful for getting the attributes and raw characters that need encoded, but you'll need to be sure to pay attention to the images too.

As for encoding in binary, Codable is completely agnostic to format, so you could write your own object conforming to Coder that does whatever you want, including store everything using raw bytes.

Aside: Other Formats

Here's a quick rundown of other supported formats (in order of size). In these tests, I used the very small string "Hello World! There's so much to see!" in the system font. After each format description (in parentheses) is the number of bytes to store that string.

  • Plain Text can store the above format in 36 bytes (1 for each character), but won't preserve attributes or attachments. (36 bytes)
  • RTF seems most lightweight if you need to preserve attributes but not attachments. (331 bytes)
  • HTML Is next lightest, but isn't really designed to be a storage format. In my experience, some attributes such as line spacing get lost when converted to HTML by NSAttributedString. (536 bytes)
  • Binary Plist, which is made when you use NSKeyedArchiver, is a fine option if you only need compatibility with Apple platforms and don't like the above formats. This format supports images too, but is generally still larger than the above (and RTFD). (648 bytes)
  • Web Archive is next for size, but I don't recommend using it as WebKit has deprecated it. Safari still uses it though for some things. (784 bytes)
  • Word ML is probably only useful for those that already know they need it. This format and all below it will generally have a bunch of boilerplate that will become a smaller percentage of the file as text is added. (~1.2 MB)
  • Open Document (OASIS) is smaller than most of the Word formats, but you probably wouldn't use it without a good reason. (~2.4 MB)
  • Office Open XML Is another format you'd only use if you needed that format exactly. (~3.5 MB)
  • Doc (Microsoft Word) This file is very large in comparison for small amounts of text. While I would expect this format to allow images, in my testing the file size did not actually go up when I added one. (~19.4 MB)
  • Mac Simple Text seems to always generate an error. (N/A)

Final Note

In the end, the encoding experience for NSAttributedString should get better as Foundation continues to adapt to Swift rather than Objective-C. You can imagine a day where NSAttributedString or some similar Swifty type conforms to Codable out of the box and can then be paired with any file format Coder.

How to make a custom class Codable?

You could provide a subclass of ThreadSafeDictionary which works with Codable Key and Value types. In my opinion it's best to pretend that we are dealing with a simple dictionary, so lets use a singleValueContainer.

class CodableThreadSafeDictionary<Key: Codable & Hashable, Value: Codable>: ThreadSafeDictionary<Key, Value>, Codable {

public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let dictionary = try container.decode(DictionaryType.self)
protectedCache = CZMutexLock(dictionary)
}

public required init(dictionaryLiteral elements: (Key, Value)...) {
var dictionary = DictionaryType()
for (key, value) in elements {
dictionary[key] = value
}
protectedCache = CZMutexLock(dictionary)
super.init()
}

public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
var dictionary = DictionaryType()
protectedCache.readLock {
dictionary = $0
}
try container.encode(dictionary)
}

}

But because of the fact that the protectedCache is a fileprivate property, you will need to put this implementation in the same file

Note!

You could consider limiting Key to just a String for a better compatibility with JSON format:

CodableThreadSafeDictionary<Key: String, Value: Codable>

How to create model for this json with codable

Simply create enum CodingKeys and implement init(from:) in struct Root to get that working.

struct Root: Decodable {
let id: Int
let name: String
let empDetails: [Emp]

enum CodingKeys: String, CodingKey {
case id, name, empDetails, data
}

struct Emp: Codable {
let address: String
let ratings: Int
let empId: Int
let empName: String
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
name = try container.decode(String.self, forKey: .name)
let details = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .empDetails)
empDetails = try details.decode([Emp].self, forKey: .data)
}
}

How to add custom transient property in Codable struct

If you don't want to decode those 4 properties, just don't include them in the CodingKeys (and don't forget to explicitly provide default values for them, so that the decoder can initialize the object properly):

struct VideoAlbum: Codable {

let id, image: String?
let video, mediaType: JSONNull?
let type, deleted, createdOn: String?
let modifiedOn: JSONNull?

var isPlaying: Bool? = nil
var currentTime: CMTime? = nil
var timeObserver: Any? = nil
var pausedByUser: Bool? = nil

enum CodingKeys: String, CodingKey {
// include only those that you want to decode/encode
case id, image, video
case mediaType = "media_type"
case type, deleted
case createdOn = "created_on"
case modifiedOn = "modified_on"
}
}

Casting to object with Codable

So, without going through a lot of design cycles and straight off the top my head, I'd consider trying Swift's generic support, for example...

struct BasicResponse<DataType>: Codable where DataType: Codable {
let success: Int
let data: [DataType]
}

Then you just need to define the implementation of DataTypes you want to use

struct User: Codable {
var name: String
}

And decode it...

let decoder = JSONDecoder()
let response = try decoder.decode(BasicResponse<User>.self, from: data)
print(response.data[0].name)

Now, I just threw this into a Playground and tested it with some basic data...

struct User: Codable {
var name: String
}

struct BasicResponse<T>: Codable where T: Codable {
let success: Int
let data: [T]
}

let data = "{\"success\": 200, \"data\": [ { \"name\":\"hello\" }]}".data(using: .utf8)!

let decoder = JSONDecoder()
do {
let response = try decoder.decode(BasicResponse<User>.self, from: data)
response.data[0].name
} catch let error {
print(error)
}

You might need to "massage" the design to better meet your needs, but it might give you a place to start



Related Topics



Leave a reply



Submit