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

Posted

技术标签:

【中文标题】从 URL 获取图像并将其附加到数组【英文标题】:Getting Image from URL and append it to array 【发布时间】:2020-04-27 22:34:47 【问题描述】:

我正在尝试从URL 获取images 并将它们附加到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

这就是我从URLimageimage 的方式:

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 吗?我卡住了..

【问题讨论】:

你的图片在 Imageview 上可见吗? @AnilKumar imageView 只是一个占位符,我在其中使用 downloaded(from: imageName!) 设置图像。我认为这就是问题所在,因为如果我只是在 real imageView 上调用 .downloaded(from: imageName!),图像就会变得可见 【参考方案1】:

我通过更改load 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)
            
        
    



有了这个,我简单地调用:

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

                
            

        

【讨论】:

以上是关于从 URL 获取图像并将其附加到数组的主要内容,如果未能解决你的问题,请参考以下文章

从 URL 获取 JSON 数组并将其转换为 Android 中的 HashMap

获取用户输入并将其存储到指针数组

如何在 Windows Phone 8.1 上从数据库中获取图像并将其显示为字节数组

我如何从用户那里接收字符串并将其分配到没有任何中间变量的指针数组中?

无法从 LocalStorage Jquery 获取数组

如何获取所有本地图像并将其加载到swift中的数组中