I have found several crash reports with the reason unexpected start state
. My code looks like this:
NSRange range = [content rangeOfString:@"<html>"];
if (range.location != NSNotFound) {
NSString *htmlStr = [content substringFromIndex:range.location];
NSAttributedString *attStr = [[NSAttributedString alloc] initWithData:[htmlStr dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
return attStr.string;
}
The crash report looks like this:
Just call your function in background thread:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
// here, call your function
dispatch_async(dispatch_get_main_queue(), ^{
// do updates on main thread
});
});
The above crash happens when you try initializing a NSAttibutedString
with html content from any other thread than the main thread.
So the solution here is to make sure the above NSAttributedString
initialization is always called from the main thread.
DispatchQueue.main.async {
let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [.documentType: NSAttributedString.DocumentType.html]
let htmlString = try? NSAttributedString(data: htmlData, options: options, documentAttributes: nil)
}
Quoting the documentation:
The HTML importer should not be called from a background thread (that is, the options dictionary includes documentType with a value of html). It will try to synchronize with the main thread, fail, and time out. Calling it from the main thread works (but can still time out if the HTML contains references to external resources, which should be avoided at all costs). The HTML import mechanism is meant for implementing something like markdown (that is, text styles, colors, and so on), not for general HTML import.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With