gpt4 book ai didi

regex - Swift-Rss 项目 - 无法在 CDATA block 内获取 img src 链接

转载 作者:行者123 更新时间:2023-11-30 13:55:25 25 4
gpt4 key购买 nike

我有一个非常烦人的问题。我正在为 Swift 开发 RSS 阅读器(使用 Xcode 7.1)。我希望我的表格 View 的每个单元格都显示每个新闻的图像。这是我的代码:

     cell.itemImageView.image = UIImage(named: "placeholder")
let news = items[indexPath.row] as MWFeedItem?
if news?.content != nil {

let htmlContent = news!.content as NSString
var imageSource = ""

let rangeOfString = NSMakeRange(0, htmlContent.length)
let regex = try? NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: [])

if htmlContent.length > 0 {
let match = regex?.firstMatchInString(htmlContent as String, options: [], range: rangeOfString)

if match != nil {
let imageURL = htmlContent.substringWithRange(match!.rangeAtIndex(2)) as NSString
print(imageURL)

if NSString(string: imageURL.lowercaseString).rangeOfString("feedburner").location == NSNotFound {
imageSource = imageURL as String

}

}
}

if imageSource != "" {
cell.itemImageView.setImageWithURL(NSURL(string: imageSource)!, placeholderImage: UIImage(named: "placeholder"))
}
else{
cell.itemImageView.image = UIImage(named: "placeholder")
}

}

所以,问题是:当 rss feed xml 文件没有 CDATA block 时,我的代码可以完美运行;在其他大多数情况下,它不起作用,因为 xml 文件内部有这样的结构:

<![CDATA[<p><a href="http://firenze.repubblica.it/cronaca/2015/11/12/news/la_denuncia_dei_genitori_di_una_scuola_di_firenze_la_mostra_divina_bellezza_vietata_ai_bambini_-127167480/?rssimage"> <img src="http://www.repstatic.it/content/nazionale/img/2015/11/12/115530091-51ce67c2-7b38-41c1-8aa5-21d51b157335.jpg" width="140" align="left" hspace="10"></a>I genitori contro la scelta del consiglio interclasse delle terze elementari dell'istituto Matteotti di fermare la gita all'esposizione "Divina Bellezza" sul...</p>]]></description><guid isPermaLink="true"><!

很明显,CDATA block 不允许我读取 img src 链接。我能做些什么?预先感谢您的帮助!

最佳答案

我使用您的正则表达式在 PlayGround 中运行以下代码,并成功从 xml 获取所有 img src url。

import Foundation

let url = NSURL(string: "http://www.repubblica.it/rss/homepage/rss2.0.xml")!
let xml = try String(contentsOfURL: url)
let regex = try NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: [])
let range = NSMakeRange(0, xml.characters.count)
regex.enumerateMatchesInString(xml, options: [], range: range) { (result, _, _) -> Void in
let nsrange = result!.rangeAtIndex(2)
let start = xml.startIndex.advancedBy(nsrange.location)
let end = start.advancedBy(nsrange.length)
print(xml[start..<end])
}

关于regex - Swift-Rss 项目 - 无法在 CDATA block 内获取 img src 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33689858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com