如果NSAttributedstring包含外部链接,我如何附加值?

问题描述 投票:-2回答:2

嗨,我想从网站上获取HTML。它有内部和外部链接。如果链接是外部链接,我如何追加字符串。顺便说一下内部链接有applewebdata://,我检查那些内部链接。但我无法理解如何检测外部链接。我想添加像»这样的东西。

内部链接href:applewebdata://外部链接href包含http://https://

An example in here

swift nsattributedstring
2个回答
1
投票

在这里你可以做什么: 枚举链接属性。 检查每个值是否是您想要的值(以“applewebdata://”开头的值)。 修改字符串的其余部分和/或链接(你的问题在那部分不清楚,我同时做了两个)。

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)
    }
}

如果需要,可以放置游乐场代码:

let htmlString = "Hello this <a href=\"http://stackoverflow.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)

-1
投票

如果链接是NSAttributedString,您可以检查字符串的值是否包含applewebdata://http://

斯威夫特4

在Swift 4中,你可以使用NSAttributedString.string获取String,String是Character值的集合:

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
}
© www.soinside.com 2019 - 2024. All rights reserved.