I am using an extension to parse HTML text into an attributed string from a dynamically retrieved post.
I notice now that my app is crashing when retrieving a post that has empty content.
extension NSAttributedString {
public convenience init?(HTMLString html: String, font: UIFont? = nil) throws {
let options: [String: Any] = [...]
guard let data = html.data(using: .utf8, allowLossyConversion: true) else {
throw NSError(domain: "Parse Error", code: 0, userInfo: nil)
}
if let font = font {
guard let attr = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil) else {
throw NSError(domain: "Parse Error", code: 0, userInfo: nil)
}
var attrs = attr.attributes(at: 0, effectiveRange: nil) //APP CRASHES HERE
attrs[NSFontAttributeName] = font
attr.setAttributes(attrs, range: NSRange(location: 0, length: attr.length))
self.init(attributedString: attr)
} else {
try? self.init(data: data, options: options, documentAttributes: nil)
}}}
Here is my exception:
'NSRangeException', reason: 'NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds'
I am not very good at handling errors yet, is there a way to prevent this exception from arising regardless of the content?
I tried a do/catch block but it says that no calls to throwing functions happen in this line:
do {
var attrs = attr.attributes(at: 0, effectiveRange: nil) //APP CRASHES HERE
attrs[NSFontAttributeName] = font
attr.setAttributes(attrs, range: NSRange(location: 0, length: attr.length))
self.init(attributedString: attr)
} catch {
print("error")
}