Question

iOS 7 allows an NSAttributedString to be initialized with an HTML file or data. I want to use this functionality to make it easier to insert links in 'About' texts of apps.

To achieve this, I initialize the NSAttributedString with the following code:

NSURL *url = [[NSBundle mainBundle] URLForResource:@"test.html" withExtension:nil];
NSError *error = nil;
NSDictionary *options = nil;
NSDictionary *attributes = nil;
_textView.attributedText = [[NSAttributedString alloc] initWithFileURL:url options:options documentAttributes:&attributes error:&error];

and a file with the following content:

<html><body>
<p>This is a <a href=\"http://www.stackoverflow.com\">test link</a>. It leads to StackOverflow.<p>
</body></html>

Update

The above HTML still had the escape marks from trying to use it in code as an NSString. Removing the escapes makes it work just fine. Also answered my own question below.

End update

This works fine, and gives a string with the url properly formatted and clickable. Clicking the link calls the UITextView's delegate -textView:shouldInteractWithURL:inRange: method. However, inspecting the URL parameter shows the URL actually has the following absolute string:

file:///%22http://www.google.com/%22

which obviously doesn't open the appropriate webpage. I don't find the documentation on NSAttributedText clear enough to determine why this happens.

Anyone know how I should initialize the NSAttributedString to generate the appropriate URL?

Was it helpful?

Solution 2

The answer to this question is that the HTML file was invalid.

Having copy/pasted the html directly from a string defined in Objective-C, I forgot to remove the escapes before each quote. This of course translated directly to a file url instead of an HTML url. Removing the escape marks fixes this.

OTHER TIPS

Try reading the HTML file into a NSString and then use:

NSString *path = [[NSBundle mainBundle] pathForResource:@"test.html" ofType:nil];
NSString *html = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
_textView.attributedText = [[NSAttributedString alloc] initWithHTML:html baseURL:nil options:options documentAttributes:&attributes];

At least this should work if it is similar with what happens in UIWebViews. The URL is resolved using the baseURL. It appears that in your code the source url is also used as baseURL. So I am passing a nil URL to prevent resolving against a local file URL.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top