How can I append value if NSAttributedstring contains external link?

时光毁灭记忆、已成空白 提交于 2019-12-13 10:58:54

问题


Hi I'm trying to get html from a website. It has internal and external links. How can I append string if link is external link. By the way internal links has applewebdata:// and I check those ones as internal. But I couldn't understand how can I detect external links. I want just add something like that » .

Internal link href: applewebdata:// External link href contains http:// or https://

An example in here


回答1:


Here what you could do:
Enumerate the link attribute.
Check for each value if it's the one you want (the one that starts with "applewebdata://").
Modify either the rest of the string and/or the link (your question is unclear on that part, I made both).

attributedString needs to be mutable (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)
    }
}

Code for Playground to put before if needed:

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)



回答2:


If the link is a NSAttributedString, you can just check if the value of the string contains applewebdata:// or http://.

Swift 4

In Swift 4, you can get the String from NSAttributedString with .string and a String is a collection of Character value:

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
}


来源:https://stackoverflow.com/questions/55249765/how-can-i-append-value-if-nsattributedstring-contains-external-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!