Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS crash report "unexpected start state" exception?

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:

enter image description here

like image 938
tom lider Avatar asked Oct 23 '17 03:10

tom lider


2 Answers

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
    });
});
like image 175
Ganpat Avatar answered Nov 13 '22 22:11

Ganpat


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.

like image 5
Crt Gregoric Avatar answered Nov 13 '22 21:11

Crt Gregoric