I use NSKeyedArchiver.archivedData
to transfer my NSAttributedString
to Data
and saved it to Realm
or UserDefaults
. Here is the extension that I implemented. It works pretty well before iOS 13
extension NSAttributedString {
func toData() -> Data {
if #available(iOS 13.0, *) {
var data = try? NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: true)
if data == nil {
data = NSKeyedArchiver.archivedData(withRootObject: self)
}
return data!
} else {
return NSKeyedArchiver.archivedData(withRootObject: self)
}
}
static func fromData(_ data: Data) -> NSAttributedString? {
var attribute: NSAttributedString?
if #available(iOS 13.0, *) {
attribute = try? NSKeyedUnarchiver.unarchivedObject(ofClass: NSAttributedString.self, from: data)
} else {
attribute = NSKeyedUnarchiver.unarchiveObject(with: data) as? NSAttributedString
}
return attribute
}
}
I encountered some issues when I transfer the Data to NSAttributedString
by using the NSKeyedUnarchiver.unarchiveObject
method
Here is the warning that I got from the logs:
CoreText note: Client requested name ".PingFangSC-Light", it will get TimesNewRomanPSMT rather than the intended font. All system UI font access should be through proper APIs such as CTFontCreateUIFontForLanguage() or +[UIFont systemFontOfSize:].
CoreText note: Client requested name ".PingFangSC-Medium", it will get TimesNewRomanPSMT rather than the intended font. All system UI font access should be through proper APIs such as CTFontCreateUIFontForLanguage() or +[UIFont systemFontOfSize:].
It happens only when it's not English and the fonts that I'm using have Light
or Bold
or Medium
font-weight. I know that I should use CTFontCreateUIFontForLanguage
to get the fonts on iOS 13.
But attribute = try? NSKeyedUnarchiver.unarchivedObject(ofClass: NSAttributedString.self, from: data)
seems doesn't work as this step doesn't involve any font changes.
Here is all the sample that I made: https://gist.github.com/MrFuFuFu/8e3778d8fb5a39e9b74211619caab4d6