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

时间:2020-04-27 22:34:47

标签: ios swift url uiimage

我正在尝试从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

这就是我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上吗?我被困住了。

1 个答案:

答案 0 :(得分:0)

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

extension UIImage {

public static func loadFrom(url: URL, completion: @escaping (_ image: UIImage?) -> ()) {
    DispatchQueue.global().async {
        if let data = try? Data(contentsOf: url) {
            DispatchQueue.main.async {
                completion(UIImage(data: data))
            }
        } else {
            DispatchQueue.main.async {
                completion(nil)
            }
        }
    }
}

}

为此,我只需致电:

for imageName in srcsStringArray {
            if (imageName?.matches("^https?://(?:[a-z0-9\\-]+\\.)+[a-z]{2,6}(?:/[^/#?]+)+\\.(?:jpg|gif|png)$"))! {

                guard let url = URL(string: imageName!) else { return }

                UIImage.loadFrom(url: url) { image in

                    if let image = image {
                        print("append")
                       self.imagesArray.append(image)
                    } else {
                        print("Image '\(String(describing: imageName))' does not exist!")
                    }

                }
            }

        }