嗨,我正在尝试从网站获取html。它具有内部和外部链接。如果链接是外部链接,如何附加字符串。顺便说一下,内部链接具有applewebdata://
,我将这些链接检查为内部链接。但是我不明白如何检测外部链接。我只想添加类似»
的内容。
内部链接href:applewebdata://
外部链接href包含http://
或https://
答案 0 :(得分:0)
您可以做什么:
枚举链接属性。
检查每个值是否都是您想要的值(以“ applewebdata://”开头的值)。
修改其余的字符串和/或链接(您的问题尚不清楚,我都做了)。
myapp-dockerfile
必须是可变的(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)
}
}
答案 1 :(得分:-1)
如果链接是NSAttributedString
,则只需检查字符串的值是否包含applewebdata://
或http://
。
在Swift 4中,您可以使用NSAttributedString
从.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
}