我正在尝试从images
中获取URL
并将其附加到array
。如果这是我的function
:
func doStuff(html: String?){
do {
let doc: Document = try SwiftSoup.parse(html ?? "")
let priceClasses: Elements? = try doc.select("[class~=(?i)price]")
for priceClass: Element in priceClasses!.array() {
let priceText : String = try priceClass.text()
print(try priceClass.className())
print("pricetext: \(priceText)")
}
let srcs: Elements = try doc.select("img[src]")
let srcsStringArray: [String?] = srcs.array().map { try? $0.attr("src").description }
for imageName in srcsStringArray {
if (imageName?.matches("^https?://(?:[a-z0-9\\-]+\\.)+[a-z]{2,6}(?:/[^/#?]+)+\\.(?:jpg|gif|png)$"))! {
print(imageName!)
let imageView = UIImageView()
imageView.downloaded(from: imageName!) {
if let image = imageView.image {
self.imagesArray!.append(image)
} else {
print("Image '\(String(describing: imageName))' does not exist!")
}
}
}
}
} catch Exception.Error( _, let message) {
print(message)
} catch {
print("error")
}
}
此代码不起作用,因为它总是退出并打印<imageName> does not exist!
。奇怪的是fileName
是正确的名称!
例如:
[这就是我从download
到image
的URL
:
extension UIImageView {
func downloaded(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() {
self.image = image
}
}.resume()
}
func downloaded(from link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit, finished: () -> Void) {
guard let url = URL(string: link) else { return }
downloaded(from: url, contentMode: mode)
finished()
}
}
没有人知道为什么我不能将images
附加到我的array
上吗?我被卡住了。
我正在尝试从URL获取图像并将其附加到数组中。这是我的函数:func doStuff(html:String?){do {let doc:Document = try SwiftSoup.parse(html ??“”)...
我通过更改load
和image
的方式解决了该问题: