如果 NSAttributedstring 包含外部链接,我如何附加值? [英] How can I append value if NSAttributedstring contains external link?

查看:85
本文介绍了如果 NSAttributedstring 包含外部链接,我如何附加值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从网站获取 html.它有内部和外部链接.如果链接是外部链接,我如何附加字符串.顺便说一下,内部链接有 applewebdata://,我将这些链接检查为内部链接.但我无法理解如何检测外部链接.我只想添加类似 » 的内容.

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 » .

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

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

此处的示例

推荐答案

您可以这样做:
枚举链接属性.
检查每个值是否是您想要的值(以applewebdata://"开头的值).
修改字符串的其余部分和/或链接(您的问题在那部分不清楚,我都做了).

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 需要是可变的(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 的代码之前:

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)

这篇关于如果 NSAttributedstring 包含外部链接,我如何附加值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆