带有超链接的HTML的NSAttributedString

时间:2018-05-03 18:50:26

标签: html swift hyperlink uitextview nsattributedstring

我正在尝试使用NSAttributedString将包含超链接的大型HTML字符串呈现到UITextView中。一切都工作正常,除了超链接,他们实际上没有打开链接。

举个例子,这是我的html字符串的虚拟版本:

let htmlString = "<html><p>If you would like to contact someone, you can email 
them at <a class=rvts10 href=\"mailto:some@one.com\">some@one.com</a></p></html>"

我有一个名为convertHTML()的函数,它使用html文档类型选项将字符串转换为NSAttributedString,我用它来分配给UITextView的属性文本:

textView.attributedText = htmlString.convertHTML()

TextField为selectable,但不是editable。加载页面时,您可以看到超链接样式(蓝色文本)和所有内容,但您无法点击链接并打开邮件应用程序。

我认为我需要将“mailto:...”更改为iOS将识别的其他内容,但我不知道需要做什么才能使此链接可链接。

这是我的html方法:

func convertHtml() -> NSAttributedString{
    guard let data = data(using: .utf8) else { return NSAttributedString() }
    do{
        return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
    }catch{
        return NSAttributedString()
    }
}

2 个答案:

答案 0 :(得分:0)

我认为你的convertHTML()方法有错误检查这个

 let htmlString = "<html><p>If you would like to contact someone, you can email them at <a class=rvts10 href=\"mailto:some@one.com\">some@one.com</a></p></html>"

            // you have to convert string to data
            let data = Data(htmlString.utf8)
            // then convert data to NSAttributedString with NSAttributedString.DocumentType.htm
            if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
                self.textView.attributedText = attributedString
            }

答案 1 :(得分:0)

我使用此扩展程序:

import Foundation

    extension NSAttributedString {

        convenience init(htmlString html: String) throws {
            try self.init(data: Data(html.utf8), options: [
                .documentType: NSAttributedString.DocumentType.html,
                .characterEncoding: String.Encoding.utf8.rawValue
                ], documentAttributes: nil)
        }

    }

实施后你可以像这样使用它:

contentTextField.attributedText = try? NSAttributedString(htmlString: aHTMLString)