使用HTML文件初始化NSAttributedString将HTTP链接解析为文件URL

时间:2013-11-02 20:13:35

标签: ios ios7 uitextview nsattributedstring uitextviewdelegate

iOS 7允许使用HTML文件或数据初始化NSAttributedString。我想使用此功能,以便更容易在“关于”应用程序文本中插入链接。

为实现此目的,我使用以下代码初始化NSAttributedString:

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];

以及包含以下内容的文件:

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

更新

上面的HTML仍然有试图在代码中使用它作为NSString的转义标记。删除逃脱使它工作得很好。还回答了我自己的问题。

结束更新

这很好用,并提供一个字符串,其中url格式正确且可点击。单击该链接将调用UITextView的委托-textView:shouldInteractWithURL:inRange:方法。但是,检查URL参数显示URL实际上具有以下绝对字符串:

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

显然没有打开相应的网页。我没有发现NSAttributedText上的文档足够清楚,以确定为什么会发生这种情况。

任何人都知道如何初始化NSAttributedString以生成适当的URL?

2 个答案:

答案 0 :(得分:1)

尝试将HTML文件读入NSString,然后使用:

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];

如果它与UIWebViews中发生的情况类似,至少应该有效。使用baseURL解析URL。在您的代码中,源网址似乎也被用作baseURL。所以我传递的是nil网址,以防止解析本地文件网址。

答案 1 :(得分:0)

这个问题的答案是HTML文件无效。

直接从Objective-C中定义的字符串复制/粘贴html,我忘了在每个引用之前删除转义。这当然直接翻译成文件网址而不是HTML网址。删除转义标记可以解决此问题。