Search code examples
core-datauikitnsattributedstringappkit

NSAttributedString - compatibility UIKit (iOS) and AppKit (macOS)


I have an application for iOS and macOS. These apps are using Cloudit to share information between (Core data). I am storing NSAttributedString created on one platform (for example iOS) in core data attribute, which is defined as Transformable type of attribute so core data uses (I assume) default NSCoder to code/decode NSAttributedString data.

Now my macOS app can read data from iCloud including this NSAttributedString and view/edit them. But this NSAttributedString looks completely different on macOS (and vice versa)

Not only size (which I understand, because default size on iOS and macOS is different - so I need to adjust size) but I lost my formatting (bold, italic, etc.).

So it seems like font attributes for UIFont and NSFont are not compatible, am I right? I am using standard fonts - for example on iOS UIFont.preferredFont(forTextStyle: .body)

Maybe I have to store NSAttributedString as something else (for example convert it to RTF/HTML data and share them that way) in iCloud and during reading convert RTF/HTML again into NSAttributedString. I am not asking how to do that (I know it) but I am asking if I have to do that to have NSAttributedString compatible (at least from formatting point of view) on all used platforms.

I cannot find anything regarding this on web (maybe I searching with wrong keywords). Does anybody have experience with sharing NSAttributedString between platforms (iOS, macOS)?. Are there are any recommendations for that?

Thanks for advice/help in advance.


Solution

  • Solution

    Finally I found the solution. The problem is that UIFont.preferredFont(forTextStyle: .body) returns a font that is not recognized on macOS platform. Therefore macOS instead of using this unknown fonts used Times New Roman for plain, bold and italic variants and this is the reason why I lost some formatting information on the way from iOS to macOS application.

    Solution is simple. Instead of using standard font returned by

    UIFont.preferredFont(forTextStyle: .body)

    it's better to use font that is available on both platforms (for example Arial). No need to convert NSAttributedString into RTF/HTML and back.