简体   繁体   中英

Getting Image from URL and append it to array

I am trying to get images from a URL and append them to an array . This if my function for it:

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")

    }
}

This code is not working as it always exits and print <imageName> does not exist! . The weird thing is that the fileName is a correct name!

For example:

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

This is how I download the image from the 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()
}
}

Does anyone have any idea why I can not append images to my array ??? Im stuck..

I fixed the issue by changing the way I load the image :

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)
            }
        }
    }
}

}

With this I simply call:

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!")
                    }

                }
            }

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM