如果 NSAttributedstring 包含外部 link,我如何追加值?

How can I append value if NSAttributedstring contains external link?

您好,我正在尝试从网站获取 html。它有内部和外部 links。如果 link 是外部 link,我如何附加字符串?顺便说一句,内部 links 有 applewebdata://,我检查那些是内部的。但我不明白如何检测外部 links。我只想添加类似 » 的内容。

内部 link href:applewebdata:// 外部 link href 包含 http://https://

An example in here

如果link是一个NSAttributedString,你可以只检查字符串的值是否包含applewebdata://http://

Swift 4

在Swift 4中,可以用.stringNSAttributedString中获取字符串,一个字符串是字符值的集合:

let link = NSAttributedString(???) // Your LINK
let stringUrl = link.string
if stringUrl.contains("applewebdata") {
    // Do something to the internal link
} else if stringUrl.contains("http") {
    // Do something to the external link
}

这里你可以做什么:
枚举 link 属性。
检查每个值是否是您想要的值(以 "applewebdata://" 开头的值)。
修改字符串的其余部分 and/or 或 link(你的问题在那部分不清楚,我都做了)。

attributedString 需要可变 (NSMutableAttributedString)。

attributedString.enumerateAttribute(.link, in: NSRange(location: 0, length: attributedString.length), options: [.reverse]) { (attribute, range, pointee) in
    if let link = attribute as? URL, link.absoluteString.hasPrefix("applewebdata://") {
        var replacement = NSMutableAttributedString(attributedString: attributedString.attributedSubstring(from: range))

        //Use replaceCharacters(in range: NSRange, with str: String) if you want to keep the same "effects" (attributes)
        replacement.replaceCharacters(in: NSRange(location: replacement.length, length: 0), with: "~~>")

        //Change the link if needed
        let newLink = link.absoluteString + "2"
        replacement.addAttribute(.link, value: newLink, range: NSRange(location: 0, length: replacement.length))

        //Replace
        attributedString.replaceCharacters(in: range, with: replacement)
    }
}

如果需要,可放在前面的 Playground 代码:

let htmlString = "Hello this <a href=\"http://whosebug.com\">external link</a> and that's an <a href=\"applewebdata://myInternalLink\">internal link</a> and that's it."
let htmlData = htmlString.data(using: .utf8)!
let attributedString = try! NSMutableAttributedString(data: htmlData,
                                                      options: [.documentType : NSAttributedString.DocumentType.html],
                                                      documentAttributes: nil)