从URL获取图像并将其附加到数组中

问题描述 投票:0回答:1

我正在尝试从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是正确的名称!

例如:

https://www.adidas.de/on/demandware.static/-/Sites-adidas-DE-Library/default/dw817801e3/Originals_Brand_Nav_Title.png

[这就是我从downloadimageURL

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 ??“”)...

ios swift url uiimage
1个回答
0
投票

我通过更改loadimage的方式解决了该问题:

© www.soinside.com 2019 - 2024. All rights reserved.