Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing NSAttributedString with HTML file parses HTTP links as file URLs

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?

like image 619
SpacyRicochet Avatar asked Nov 12 '22 19:11

SpacyRicochet


1 Answers

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.

like image 124
gimenete Avatar answered Dec 04 '22 05:12

gimenete